Viewer refactor with state sync (#212)

* initial commit for viewer refactor

* updating name change to nerfactory

* adding headers

* making the rendering fix which broke from a merge

* things are starting to work. removing old commands now

* removed prints

* cleanup

* updating state works now even for nested dictionaries

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

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

* images and frustums drawn correctly

* fixing lint

* github actions

* back to npm

* fixing eslint

* remove package.json from root

* new favicon

* some viewer cleanup

* notebook

* fixed camera drawings speed to avoid redraw

* trying to get Leva to update

* quick fix

* synced config panel

* adding notebook

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

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
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;
}
+18
View File
@@ -0,0 +1,18 @@
import './App.css';
import React from 'react';
import { RenderControls } from './modules/ConfigPanel/ConfigPanel';
import SetupScene from './modules/Scene/Scene';
import ViewerWindow from './modules/ViewerWindow/ViewerWindow';
export default function App() {
const scene = SetupScene();
return (
<div className="App">
<RenderControls />
<ViewerWindow scene={scene} />
</div>
);
}
@@ -1,282 +0,0 @@
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);
}
}
}
+34 -33
View File
@@ -1,12 +1,14 @@
import * as THREE from "three";
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-restricted-syntax */
import * as THREE from 'three';
const dat = require("dat.gui");
const dat = require('dat.gui');
function remove_folders(gui) {
for (let name of Object.keys(gui.__folders)) {
let folder = gui.__folders[name];
for (const name of Object.keys(gui.__folders)) {
const folder = gui.__folders[name];
remove_folders(folder);
dat.dom.dom.unbind(window, "resize", folder.__resizeHandler);
dat.dom.dom.unbind(window, 'resize', folder.__resizeHandler);
gui.removeFolder(folder);
}
}
@@ -20,7 +22,7 @@ function dispose(object) {
}
if (object.material) {
if (Array.isArray(object.material)) {
for (let material of object.material) {
for (const material of object.material) {
if (material.map) {
material.map.dispose();
}
@@ -35,42 +37,41 @@ function dispose(object) {
}
}
export class SceneNode {
export default class SceneNode {
constructor(object, folder) {
this.object = object;
this.folder = folder;
this.children = {};
this.create_controls();
for (let c of this.object.children) {
for (const 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);
const f = this.folder.addFolder(object.name);
const node = new SceneNode(object, f);
this.children[object.name] = node;
return node;
}
create_child(name) {
let obj = new THREE.Group();
const obj = new THREE.Group();
obj.name = name;
this.object.add(obj);
return this.add_child(obj);
}
find(path) {
if (path.length == 0) {
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));
}
const name = path[0];
let child = this.children[name];
if (child === undefined) {
child = this.create_child(name);
}
return child.find(path.slice(1));
}
create_controls() {
@@ -79,19 +80,19 @@ export class SceneNode {
}
this.vis_controller = new dat.controllers.BooleanController(
this.object,
"visible"
'visible',
);
this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
this.vis_controller.domElement.style.float = "right";
this.vis_controller.domElement.style.height = '0';
this.vis_controller.domElement.style.float = 'right';
}
set_property(property, value) {
if (property === "position") {
if (property === 'position') {
this.object.position.set(value[0], value[1], value[2]);
} else if (property === "quaternion") {
} else if (property === 'quaternion') {
this.object.quaternion.set(value[0], value[1], value[2], value[3]);
} else if (property === "scale") {
} else if (property === 'scale') {
this.object.scale.set(value[0], value[1], value[2]);
} else {
this.object[property] = value;
@@ -100,17 +101,17 @@ export class SceneNode {
}
set_transform(matrix) {
let mat = new THREE.Matrix4();
const mat = new THREE.Matrix4();
mat.fromArray(matrix);
mat.decompose(
this.object.position,
this.object.quaternion,
this.object.scale
this.object.scale,
);
}
set_object(object) {
let parent = this.object.parent;
const parent = this.object.parent;
this.dispose_recursive();
this.object.parent.remove(this.object);
this.object = object;
@@ -119,19 +120,19 @@ export class SceneNode {
}
dispose_recursive() {
for (let name of Object.keys(this.children)) {
for (const name of Object.keys(this.children)) {
this.children[name].dispose_recursive();
}
dispose(this.object);
}
delete(path) {
if (path.length == 0) {
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];
const parent = this.find(path.slice(0, path.length - 1));
const name = path[path.length - 1];
const child = parent.children[name];
if (child !== undefined) {
child.dispose_recursive();
parent.object.remove(child.object);
-461
View File
@@ -1,461 +0,0 @@
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
@@ -1,68 +0,0 @@
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
@@ -1,43 +0,0 @@
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
@@ -1,32 +0,0 @@
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();
+15
View File
@@ -0,0 +1,15 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import App from './App';
import WebSocketProvider from './modules/WebSocket/WebSocket';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<WebSocketProvider>
<App />
</WebSocketProvider>
</Provider>,
);
-7
View File
@@ -1,7 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 2.6 KiB

Whitespace-only changes.
@@ -0,0 +1,252 @@
import { button, buttonGroup, useControls } from 'leva';
import { useContext, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { WebSocketContext } from '../WebSocket/WebSocket';
const msgpack = require('msgpack-lite');
export function RenderControls() {
// connection status indicators
const websocket = useContext(WebSocketContext).socket;
const isWebsocketConnected = useSelector(
(state) => state.websocketState.isConnected,
);
const isWebrtcConnected = useSelector(
(state) => state.webrtcState.isConnected,
);
const isTraining = useSelector((state) => state.renderingState.isTraining);
const outputOptions = useSelector(
(state) => state.renderingState.output_options,
);
const outputChoice = useSelector(
(state) => state.renderingState.output_choice,
);
const min_resolution = useSelector(
(state) => state.renderingState.minResolution,
);
const max_resolution = useSelector(
(state) => state.renderingState.maxResolution,
);
const field_of_view = useSelector(
(state) => state.renderingState.field_of_view,
);
const dispatch = useDispatch();
const set_min_resolution = (value) => {
if (websocket.readyState === WebSocket.OPEN) {
dispatch({
type: 'write',
path: 'renderingState/minResolution',
data: value,
});
const cmd = 'write';
const path = 'renderingState/minResolution';
const data = {
type: cmd,
path,
data: value,
};
const message = msgpack.encode(data);
websocket.send(message);
}
};
const set_max_resolution = (value) => {
if (websocket.readyState === WebSocket.OPEN) {
dispatch({
type: 'write',
path: 'renderingState/maxResolution',
data: value,
});
const cmd = 'write';
const path = 'renderingState/maxResolution';
const data = {
type: cmd,
path,
data: value,
};
const message = msgpack.encode(data);
websocket.send(message);
}
};
const set_output_choice = (value) => {
if (websocket.readyState === WebSocket.OPEN) {
dispatch({
type: 'write',
path: 'renderingState/output_choice',
data: value,
});
const cmd = 'write';
const path = 'renderingState/output_choice';
const data = {
type: cmd,
path,
data: value,
};
const message = msgpack.encode(data);
websocket.send(message);
}
};
const set_fov = (value) => {
if (websocket.readyState === WebSocket.OPEN) {
dispatch({
type: 'write',
path: 'renderingState/field_of_view',
data: value,
});
const cmd = 'write';
const path = 'renderingState/field_of_view';
const data = {
type: cmd,
path,
data: value,
};
const message = msgpack.encode(data);
websocket.send(message);
}
};
const [, setControls] = useControls(
'Rendering State',
() => ({
// WebSocket isConnected
// button does nothing except be an indicator
'WebSocket Connected': button(() => {}, {
disabled: !isWebsocketConnected,
}),
// webRTC isConnected
// button does nothing except be an indicator
'WebRTC Connected': button(() => {}, {
disabled: !isWebrtcConnected,
}),
// isTraining
'Pause Training': button(
() => {
// write locally to store
dispatch({
type: 'write',
path: 'renderingState/isTraining',
data: false,
});
// write to server
const cmd = 'write';
const path = 'renderingState/isTraining';
const data = {
type: cmd,
path,
data: false,
};
const message = msgpack.encode(data);
websocket.send(message);
},
{
disabled: !isTraining,
},
),
'Resume Training': button(
() => {
// write locally to store
dispatch({
type: 'write',
path: 'renderingState/isTraining',
data: true,
});
// write to server
const cmd = 'write';
const path = 'renderingState/isTraining';
const data = {
type: cmd,
path,
data: true,
};
const message = msgpack.encode(data);
websocket.send(message);
},
{
disabled: isTraining,
},
),
// output_options
output_options: {
label: 'Output Render',
options: outputOptions,
value: outputChoice,
onChange: (v) => {
set_output_choice(v);
},
},
// resolution
min_resolution: {
label: 'Min Res.',
value: min_resolution,
min: 10,
max: 100,
step: 1,
onChange: (v) => {
set_min_resolution(v);
},
},
' ': 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.',
value: max_resolution,
min: 10,
max: 2048,
step: 1,
onChange: (v) => {
set_max_resolution(v);
},
},
' ': buttonGroup({
'128px': () => setControls({ max_resolution: 128 }),
'256px': () => setControls({ max_resolution: 256 }),
'512px': () => setControls({ max_resolution: 512 }),
'1024px': () => setControls({ max_resolution: 1024 }),
}),
'Camera FoV': {
value: field_of_view,
onChange: (v) => {
set_fov(v);
},
},
}),
[
isWebsocketConnected,
isWebrtcConnected,
isTraining,
outputOptions,
outputChoice,
min_resolution,
max_resolution,
field_of_view,
],
);
useEffect(() => {
setControls({ min_resolution });
setControls({ max_resolution });
setControls({ output_options: outputChoice });
setControls({ 'Camera FoV': field_of_view });
}, [
setControls,
isWebsocketConnected,
isWebrtcConnected,
isTraining,
outputOptions,
outputChoice,
min_resolution,
max_resolution,
field_of_view,
]);
return null;
}
@@ -0,0 +1,6 @@
// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state) => state.counter.value)`
export const selectTrainingState = (state) =>
state.shared.rendering.training_state;
export const selectOutputOptions = (state) => state.shared.output_options;
@@ -0,0 +1,5 @@
#datgui {
position: absolute;
top: 2px;
left: 2px;
}
@@ -0,0 +1,127 @@
import './Scene.css';
/* eslint-disable no-restricted-syntax */
import * as THREE from 'three';
import { useContext, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { GUI } from 'dat.gui';
import SceneNode from '../../SceneNode';
import { subscribe_to_changes } from '../../subscriber';
import { WebSocketContext } from '../WebSocket/WebSocket';
import { drawCamera, drawSceneBounds } from './drawing';
const msgpack = require('msgpack-lite');
// manages setting up the scene and other logic for keeping state in sync with the server
export default function SetupScene() {
let scene = null;
let gui = null;
let sceneTree = null;
// the websocket context
const socket = useContext(WebSocketContext).socket;
const dispatch = useDispatch();
// Scene
scene = new THREE.Scene();
// GUI
gui = new GUI();
gui.domElement.id = 'datgui';
const sceneFolder = gui.addFolder('Scene');
sceneFolder.open();
sceneTree = new SceneNode(scene, sceneFolder);
// add objects to the the scene tree
const setObject = (path, object) => {
sceneTree.find(path.concat(['<object>'])).set_object(object);
};
const deleteObject = (path) => {
sceneTree.delete(path);
};
// Axes
const axes = new THREE.AxesHelper(5);
setObject(['Axes'], axes);
// Grid
const grid = new THREE.GridHelper(20, 20);
grid.rotateX(Math.PI / 2); // rotated to xy plane
setObject(['Grid'], grid);
// Lights
const color = 0xffffff;
const intensity = 1;
const light = new THREE.AmbientLight(color, intensity);
setObject(['Light'], light);
// draw scene bounds
const selector_fn_scene_bounds = (state) => {
return state.sceneState.sceneBounds;
};
const fn_value_scene_bounds = (previous, current) => {
if (current !== null) {
const line = drawSceneBounds(current);
setObject(['Scene Bounds'], line);
} else {
deleteObject(['Scene Bounds']);
}
};
subscribe_to_changes(selector_fn_scene_bounds, fn_value_scene_bounds);
// draw camera
// NOTE: this has some issues right now! it won't
// update the camera on an individual change w/o deleting first
const selector_fn_cameras = (state) => {
return state.sceneState.cameras;
};
const fn_value_cameras = (previous, current) => {
if (current !== null) {
let prev = new Set();
if (previous !== null) {
prev = new Set(Object.keys(previous));
}
const curr = new Set(Object.keys(current));
// valid if in current but not previous
// invalid if in previous but not current
for (const key of curr) {
// valid so draw
if (!prev.has(key)) {
// keys_valid.push(key);
const json = current[key];
const camera = drawCamera(json);
setObject(['Cameras', key], camera);
}
}
for (const key of prev) {
// invalid so delete
if (!curr.has(key) || current[key] === null) {
// keys_invalid.push(key);
deleteObject(['Cameras', key]);
}
}
} else {
deleteObject(['Cameras']);
}
};
subscribe_to_changes(selector_fn_cameras, fn_value_cameras);
useEffect(() => {
socket.addEventListener('message', (originalCmd) => {
// set the remote description when the offer is received
const cmd = msgpack.decode(new Uint8Array(originalCmd.data));
if (cmd.type === 'write') {
// write to the store
dispatch({
type: 'write',
path: cmd.path,
data: cmd.data,
});
}
});
}, []); // empty dependency array means only run once
return scene;
}
@@ -0,0 +1,164 @@
/* eslint-disable no-restricted-syntax */
// ---- code for drawing with three.js ----
import * as THREE from 'three';
export function drawSceneBounds(sceneBounds): THREE.Object3D {
console.assert(
sceneBounds.type === 'aabb',
'The scene bounds must be an AABB',
);
const box = sceneBounds;
const w = 1.0;
const aaa = new THREE.Vector3(w, w, w);
const aab = new THREE.Vector3(w, w, -w);
const aba = new THREE.Vector3(w, -w, w);
const baa = new THREE.Vector3(-w, w, w);
const abb = new THREE.Vector3(w, -w, -w);
const bba = new THREE.Vector3(-w, -w, w);
const bab = new THREE.Vector3(-w, w, -w);
const bbb = new THREE.Vector3(-w, -w, -w);
let points = [aaa, aab, aaa, aba, aab, abb, aba, abb];
points = points.concat([baa, bab, baa, bba, bab, bbb, bba, bbb]);
points = points.concat([aaa, baa, aab, bab, aba, bba, abb, bbb]);
const maxPoint = new THREE.Vector3(...box.max_point);
const minPoint = new THREE.Vector3(...box.min_point);
const lengths = maxPoint.clone();
lengths.sub(minPoint);
const scalar = lengths.clone();
scalar.divide(new THREE.Vector3(2.0, 2.0, 2.0));
const offset = minPoint.clone();
offset.add(scalar);
for (let i = 0; i < points.length; i += 1) {
points[i] = points[i].clone();
points[i].multiply(scalar).add(offset);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x000000,
linewidth: 1,
});
const lines = new THREE.LineSegments(geometry, material);
return lines;
}
export function getCameraWireframe(
scale = 0.3,
focalLength = 4,
w = 1.5,
h = 2,
) {
// Returns a wireframe of a 3D line-plot of a camera symbol.
// A wireframe is a frustum.
// https://github.com/hangg7/mvs_visual/blob/275d382a824733a3187a8e3147be184dd6f14795/mvs_visual.py#L54.
// scale: scale of rendering
// focalLength: this is the focal length
// w: width
// h: height
const f = focalLength;
const ul = new THREE.Vector3(-w, h, -f);
const ur = new THREE.Vector3(w, h, -f);
const ll = new THREE.Vector3(-w, -h, -f);
const lr = new THREE.Vector3(w, -h, -f);
const C = new THREE.Vector3(0, 0, 0);
const points = [
C,
ul,
C,
ur,
C,
ll,
C,
lr,
C,
ul,
ur,
ul,
lr,
ur,
lr,
ll,
ll,
ul,
];
const scalar = new THREE.Vector3(scale, scale, scale);
for (let i = 0; i < points.length; i += 1) {
points[i].multiply(scalar);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x000000,
linewidth: 1,
});
const lines = new THREE.LineSegments(geometry, material);
return lines;
}
export function drawCameraImagePlane(width, height, imageString) {
// imageString is the texture as a base64 string
const geometry = new THREE.PlaneGeometry(width, height);
const material = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
});
const texture = new THREE.TextureLoader().load(imageString);
material.map = texture;
const plane = new THREE.Mesh(geometry, material);
return plane;
}
function transpose(matrix) {
return matrix[0].map((col, i) => matrix.map((row) => row[i]));
}
export function drawCamera(camera): THREE.Object3D {
const group = new THREE.Group();
// console.log(camera);
console.assert(
camera.type === 'PinholeCamera',
'The camera should be a PinholeCamera',
);
const height = 0.25;
const f = camera.fx;
const displayedFocalLength = height / (2.0 * (camera.cy / f));
const width = 2.0 * (camera.cx / f) * displayedFocalLength;
const cameraWireframeObject = getCameraWireframe(1.0, displayedFocalLength, width, height);
cameraWireframeObject.translateZ(displayedFocalLength); // move the wireframe frustum back
group.add(cameraWireframeObject);
const cameraImagePlaneObject = drawCameraImagePlane(
width*2,
height*2,
camera.image,
);
group.add(cameraImagePlaneObject);
// make homogeneous coordinates and then
// transpose and flatten the matrix into an array
let c2w = JSON.parse(JSON.stringify(camera.camera_to_world));
c2w.push([0, 0, 0, 1]);
c2w = transpose(c2w).flat();
const mat = new THREE.Matrix4();
mat.fromArray(c2w);
mat.decompose(group.position, group.quaternion, group.scale);
return group;
}
export function drawCameras(cameras): Record<number, THREE.Object3D> {
const cameraObjects = {};
for (const [key, camera] of Object.entries(cameras)) {
cameraObjects[key] = drawCamera(camera);
}
return cameraObjects;
}
@@ -0,0 +1,27 @@
.WebRTCVideo {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
.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%;
}
@@ -0,0 +1,116 @@
import './ViewerWindow.css';
import * as THREE from 'three';
import React, { useContext, useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import WebRtcWindow from '../WebRtcWindow/WebRtcWindow';
import { WebSocketContext } from '../WebSocket/WebSocket';
const msgpack = require('msgpack-lite');
// manages a camera and the web rtc stream...
export default function ViewerWindow(props) {
// eslint-disable-next-line react/prop-types
const scene = props.scene;
let cameraControls = null;
const myRef = useRef(null);
const websocket = useContext(WebSocketContext).socket;
const field_of_view = useSelector(
(state) => state.renderingState.field_of_view,
);
const getViewportWidth = () => {
return window.innerWidth - (window.innerWidth % 2);
};
const getViewportHeight = () => {
return window.innerHeight;
};
let viewportWidth = getViewportWidth();
let viewportHeight = getViewportHeight();
const camera = new THREE.PerspectiveCamera(
field_of_view,
viewportWidth / viewportHeight,
0.01,
100,
);
camera.position.x = 5;
camera.position.y = -5;
camera.position.z = 5;
camera.up = new THREE.Vector3(0, 0, 1);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(viewportWidth, viewportHeight);
renderer.domElement.style.border = '1px solid black';
const handleResize = () => {
viewportWidth = getViewportWidth();
viewportHeight = getViewportHeight();
camera.aspect = viewportWidth / viewportHeight;
camera.updateProjectionMatrix();
renderer.setSize(viewportWidth, viewportHeight);
};
const sendCamera = () => {
// update the camera information in the python server
if (websocket.readyState === WebSocket.OPEN) {
const cmd = 'write';
const path = 'renderingState/camera';
const data = {
type: cmd,
path,
data: camera.toJSON(),
};
const message = msgpack.encode(data);
websocket.send(message);
}
};
const update = () => {
handleResize();
camera.updateProjectionMatrix();
cameraControls.update();
requestAnimationFrame(update);
renderer.render(scene, camera);
sendCamera();
};
// similar to componentDidMount
useEffect(() => {
myRef.current.append(renderer.domElement);
// add camera controls
cameraControls = new OrbitControls(camera, renderer.domElement);
cameraControls.rotateSpeed = 2.0;
cameraControls.zoomSpeed = 0.3;
cameraControls.panSpeed = 0.2;
cameraControls.target.set(0, 0, 0); // focus point of the controls
cameraControls.autoRotate = false;
cameraControls.enableDamping = true;
cameraControls.dampingFactor = 1.0;
cameraControls.update();
update();
}, []);
// useEffect(() => {
// camera.fov = field_of_view;
// console.log(field_of_view);
// camera.updateProjectionMatrix();
// }, [field_of_view]);
return (
<div>
{/* the webrtc viewer needs to know the camera pose */}
<WebRtcWindow />
<div className="canvas-container-main" ref={myRef} />
</div>
);
}
Whitespace-only changes.
@@ -0,0 +1,147 @@
import React, { createContext, useContext, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { WebSocketContext } from '../WebSocket/WebSocket';
const WebRtcContext = createContext(null);
const msgpack = require('msgpack-lite');
export { WebRtcContext };
export default function WebRtcWindow() {
const websocket = useContext(WebSocketContext).socket;
const pcRef = useRef(null);
const localVideoRef = useRef(null);
const dispatch = useDispatch();
const getRTCPeerConnection = () => {
const 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
pc.addEventListener('track', (evt) => {
dispatch({
type: "write",
path: 'webrtcState/isConnected',
data: true,
});
if (evt.track.kind === 'video') {
[localVideoRef.current.srcObject] = evt.streams; // uses array destructuring
}
});
pc.addTransceiver('video', { direction: 'recvonly' });
// for updating the status of the peer connection
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState === 'connected') {
dispatch({
type: "write",
path: 'webrtcState/isConnected',
data: true,
});
} else if (pc.iceConnectionState === 'disconnected') {
dispatch({
type: "write",
path: 'webrtcState/isConnected',
data: false,
});
}
};
return pc;
};
const sendOffer = () => {
pcRef.current
.createOffer()
.then((offer) => {
return pcRef.current.setLocalDescription(offer);
})
.then(() => {
// wait for ICE gathering to complete
return new Promise((resolve) => {
if (pcRef.current.iceGatheringState === 'complete') {
resolve();
} else {
const checkState = () => {
if (pcRef.current.iceGatheringState === 'complete') {
pcRef.current.removeEventListener(
'icegatheringstatechange',
checkState,
);
resolve();
}
};
pcRef.current.addEventListener(
'icegatheringstatechange',
checkState,
);
}
});
})
.then(() => {
// send the offer
const offer = pcRef.current.localDescription;
const cmd = 'offer';
const path = '';
const data = {
type: cmd,
path,
data: {
sdp: offer.sdp,
type: offer.type,
},
};
const message = msgpack.encode(data);
websocket.send(message);
});
};
useEffect(() => {
websocket.addEventListener('message', (originalCmd) => {
// set the remote description when the offer is received
const cmd = msgpack.decode(new Uint8Array(originalCmd.data));
if (cmd.type === 'answer') {
const answer = cmd.data;
pcRef.current.setRemoteDescription(answer);
}
});
websocket.addEventListener('open', () => {
// connect webrtc when the websocket is connected
pcRef.current = getRTCPeerConnection();
sendOffer();
});
}, []); // empty dependency array means only run once
return (
<div className="WebRTCVideo">
<video
className="WebRTCVideo-video"
autoPlay
playsInline
muted
ref={localVideoRef}
/>
</div>
);
}
@@ -0,0 +1,86 @@
// Much of this code comes from or is inspired by:
// https://www.pluralsight.com/guides/using-web-sockets-in-your-reactredux-app
import React, { createContext } from 'react';
import PropTypes from 'prop-types';
import { useDispatch } from 'react-redux';
const WebSocketContext = createContext(null);
export { WebSocketContext };
function getWebsocketEndpointFromUrl(url: string) {
const splitUrl = url.split('?');
if (splitUrl.length !== 2) {
window.alert("There should be exactly one '?' in the url.");
return '';
}
const endpoint = splitUrl.pop();
if (endpoint === '') {
const message =
'Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051';
window.alert(message);
return '';
}
return endpoint;
}
export default function WebSocketContextFunction({ children }) {
const dispatch = useDispatch();
let socket;
let ws;
// should look like ws://localhost:8051
const websocketEndpoint = getWebsocketEndpointFromUrl(window.location.href);
const connect = () => {
socket = new WebSocket(`ws://${websocketEndpoint}/`);
socket.binaryType = 'arraybuffer';
socket.onopen = () => {
dispatch({
type: 'write',
path: 'websocketState/isConnected',
data: true,
});
};
socket.onclose = () => {
// when closed, the websocket will try to reconnect every second
dispatch({
type: 'write',
path: 'websocketState/isConnected',
data: false,
});
setTimeout(() => {
connect();
}, 1000);
};
socket.onerror = (err) => {
console.error(
'Socket encountered error: ',
err.message,
'Closing socket',
);
socket.close();
};
};
if (!socket) {
connect();
ws = {
socket,
};
}
return (
<WebSocketContext.Provider value={ws}>{children}</WebSocketContext.Provider>
);
}
WebSocketContextFunction.propTypes = {
children: PropTypes.node.isRequired,
};
+59
View File
@@ -0,0 +1,59 @@
import { split_path } from './utils';
const initialState = {
// the websocket connection state
websocketState: {
isConnected: false,
},
// the webrtc connection state
webrtcState: {
isConnected: false,
},
// the rendering state
renderingState: {
camera: null, // the camera object used to render the three.js scene
isTraining: true,
output_options: ['rgb'], // populated by the possible Graph outputs
output_choice: 'rgb', // the selected output
minResolution: 50,
maxResolution: 512,
field_of_view: 80
},
// the scene state
sceneState: {
sceneBounds: null,
cameras: null,
},
// ------------------------------------------------------------------------
// which of the state keys to synchronize with the bridge server
sync_keys: ['renderingState', 'sceneState'],
};
function setData(newState, state, path, data) {
if (path.length === 1) {
newState[path[0]] = data; // eslint-disable-line no-param-reassign
} else {
newState[path[0]] = { ...state[path[0]] }; // eslint-disable-line no-param-reassign
setData(newState[path[0]], state[path[0]], path.slice(1), data);
}
}
// Use the initialState as a default value
// eslint-disable-next-line default-param-last
export default function rootReducer(state = initialState, action) {
// The reducer normally looks at the action type field to decide what happens
switch (action.type) {
case 'write': {
const path = split_path(action.path); // convert string with "/"s to a list
const data = action.data;
const newState = { ...state };
setData(newState, state, path, data);
return newState;
}
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state;
}
}
-141
View File
@@ -1,141 +0,0 @@
// 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);
});
}
}
+4
View File
@@ -0,0 +1,4 @@
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducer';
export default configureStore({ reducer: rootReducer });
+19
View File
@@ -0,0 +1,19 @@
import { useContext } from 'react';
import { ReactReduxContext } from 'react-redux';
export function subscribe_to_changes(selector_fn, fn) {
// selector_fn: returns a value from the redux state
// fn_valid: function to run on a valid input
// fn_null: function to run on a null input
const { store } = useContext(ReactReduxContext);
let current;
const handleChange = () => {
const previous = current;
current = selector_fn(store.getState());
if (previous !== current) {
fn(previous, current);
}
};
store.subscribe(handleChange);
}