Merge branch 'master' of github.com:pyradiance/radiance

This commit is contained in:
evonneng committed 2022-07-07 23:38:48 +00:00
commit e837f8dbef
36 files changed
+917 -11387

No files matched your search

+3 -1
View File
@@ -15,7 +15,9 @@
"react-scripts": "^5.0.1",
"socket.io-client": "^4.5.1",
"three": "^0.142.0",
"websocket": "^1.0.34"
"websocket": "^1.0.34",
"three-wtm": "^1.0",
"wwobjloader2": "^4.0"
},
"scripts": {
"start": "react-scripts start",
-234
View File
@@ -1,234 +0,0 @@
import * as THREE from 'three';
import CCapture from 'ccapture.js'; //TODO(ethan): check if this is correct
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);
}
}
export class Animator {
constructor(viewer) {
this.viewer = viewer;
this.folder = this.viewer.gui.addFolder("Animations");
this.mixer = new THREE.AnimationMixer();
this.loader = new THREE.ObjectLoader();
this.clock = new THREE.Clock();
this.actions = [];
this.playing = false;
this.time = 0;
this.time_scrubber = null;
this.setup_capturer("png");
this.duration = 0;
}
setup_capturer(format) {
this.capturer = new CCapture({
format: format,
name: "pyrad_" + String(Date.now())
});
this.capturer.format = format;
}
play() {
this.clock.start();
// this.mixer.timeScale = 1;
for (let action of this.actions) {
action.play();
}
this.playing = true;
}
record() {
this.reset();
this.play();
this.recording = true;
this.capturer.start();
}
pause() {
// this.mixer.timeScale = 0;
this.clock.stop();
this.playing = false;
if (this.recording) {
this.stop_capture();
this.save_capture();
}
}
stop_capture() {
this.recording = false;
this.capturer.stop();
this.viewer.animate(); // restore the animation loop which gets disabled by capturer.stop()
}
save_capture() {
this.capturer.save();
if (this.capturer.format === "png") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
} else if (this.capturer.format === "jpg") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.jpg \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
}
}
display_progress(time) {
this.time = time;
if (this.time_scrubber !== null) {
this.time_scrubber.updateDisplay();
}
}
seek(time) {
this.actions.forEach((action) => {
action.time = Math.max(0, Math.min(action._clip.duration, time));
});
this.mixer.update(0);
this.viewer.set_dirty();
}
reset() {
for (let action of this.actions) {
action.reset();
}
this.display_progress(0);
this.mixer.update(0);
this.setup_capturer(this.capturer.format);
this.viewer.set_dirty();
}
clear() {
remove_folders(this.folder);
this.mixer.stopAllAction();
this.actions = [];
this.duration = 0;
this.display_progress(0);
this.mixer = new THREE.AnimationMixer();
}
load(animations, options) {
this.clear();
this.folder.open();
let folder = this.folder.addFolder("default");
folder.open();
folder.add(this, "play");
folder.add(this, "pause");
folder.add(this, "reset");
// Note, for some reason when you call `.max()` on a slider controller it does
// correctly change how the slider behaves but does not change the range of values
// that can be entered into the text box attached to the slider. Oh well. We work
// around this by creating the slider with an unreasonably huge range and then calling
// `.min()` and `.max()` on it later.
this.time_scrubber = folder.add(this, "time", 0, 1e9, 0.001);
this.time_scrubber.onChange((value) => this.seek(value));
folder.add(this.mixer, "timeScale").step(0.01).min(0);
let recording_folder = folder.addFolder("Recording");
recording_folder.add(this, "record");
recording_folder.add({format: "png"}, "format", ["png", "jpg"]).onChange(value => {
this.setup_capturer(value);
});
if (options.play === undefined) {
options.play = true
}
if (options.loopMode === undefined) {
options.loopMode = THREE.LoopRepeat
}
if (options.repetitions === undefined) {
options.repetitions = 1
}
if (options.clampWhenFinished === undefined) {
options.clampWhenFinished = true
}
this.duration = 0;
this.progress = 0;
for (let animation of animations) {
let target = this.viewer.scene_tree.find(animation.path).object;
let clip = this.loader.parseAnimations([animation.clip])[0];
let action = this.mixer.clipAction(clip, target);
action.clampWhenFinished = options.clampWhenFinished;
action.setLoop(options.loopMode, options.repetitions);
this.actions.push(action);
this.duration = Math.max(this.duration, clip.duration);
}
this.time_scrubber.min(0);
this.time_scrubber.max(this.duration);
this.reset();
if (options.play) {
this.play();
}
}
update() {
if (this.playing) {
this.mixer.update(this.clock.getDelta());
this.viewer.set_dirty();
if (this.duration != 0) {
let current_time = this.actions.reduce((acc, action) => {
return Math.max(acc, action.time);
}, 0);
this.display_progress(current_time);
} else {
this.display_progress(0);
}
if (this.actions.every((action) => action.paused)) {
this.pause();
for (let action of this.actions) {
action.reset();
}
}
}
}
after_render() {
if (this.recording) {
this.capturer.capture(this.viewer.renderer.domElement);
}
}
}
// Generates a gradient texture without filling up
// an entire canvas. We simply create a 2x1 image
// containing only the two colored pixels and then
// set up the appropriate magnification and wrapping
// modes to generate the gradient automatically
function gradient_texture(top_color, bottom_color) {
let colors = [bottom_color, top_color];
let width = 1;
let height = 2;
let size = width * height;
var data = new Uint8Array(3 * size);
for (let row = 0; row < height; row++) {
let color = colors[row];
for (let col = 0; col < width; col++) {
let i = 3 * (row * width + col);
for (let j = 0; j < 3; j++) {
data[i + j] = color[j];
}
}
}
var texture = new THREE.DataTexture(data, width, height, THREE.RGBFormat);
texture.magFilter = THREE.LinearFilter;
texture.encoding = THREE.LinearEncoding;
// By default, the points in our texture map to the center of
// the pixels, which means that the gradient only occupies
// the middle half of the screen. To get around that, we just have
// to tweak the UV transform matrix
texture.matrixAutoUpdate = false;
texture.matrix.set(0.5, 0, 0.25,
0, 0.5, 0.25,
0, 0, 1);
texture.needsUpdate = true
return texture;
}
-19
View File
@@ -1,19 +0,0 @@
import React, { Component } from "react";
export class BackgroundDiv extends Component {
componentDidMount() {
document.getElementById("BackgroundDiv-video").play();
}
render() {
return (
<div className="BackgroundDiv">
<video id="BackgroundDiv-video" autoPlay muted loop>
<source
src="https://www.w3schools.com/html/mov_bbb.mp4"
type="video/mp4"
></source>
</video>{" "}
</div>
);
}
}
@@ -2,7 +2,7 @@ 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 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.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";
@@ -193,11 +193,10 @@ export class ExtensibleObjectLoader extends THREE.ObjectLoader {
if (json.mtl_library) {
let mtl_loader = new MTLLoader(manager);
let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", "");
console.log(mtl_parse_result);
// let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result);
// console.log(materials);
// loader.addMaterials(materials);
// this.onTextureLoad();
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);
+120 -120
View File
@@ -3,142 +3,142 @@ 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);
}
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();
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();
}
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);
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));
add_child(object) {
let f = this.folder.addFolder(object.name);
let node = new SceneNode(object, f);
this.children[object.name] = node;
return node;
}
}
create_controls() {
if (this.vis_controller !== undefined) {
this.folder.domElement.removeChild(this.vis_controller.domElement);
create_child(name) {
let obj = new THREE.Group();
obj.name = name;
this.object.add(obj);
return this.add_child(obj);
}
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;
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));
}
}
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();
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";
}
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];
}
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];
}
}
}
}
-374
View File
@@ -1,374 +0,0 @@
import React, { Component } from "react";
import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
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 Viewer 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();
}
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);
}
}
set_object(path, object) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
// add controls if object is a camera
if (object instanceof THREE.Camera) {
this.state.controls_main = new TrackballControls(
object,
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.staticMoving = false; // false is default
this.state.controls_main.target.set(0, 0, 0); // focus point of the controls
this.state.controls_main.autoRotate = false;
this.state.controls_main.dynamicDampingFactor = 1.0;
this.state.controls_main.update();
// this.send_camera_over_websocket();
// this.state.controls_main.addEventListener("change", () => {
// this.send_camera_over_websocket();
// });
}
}
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);
}
// 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.set_object(["Cameras", "Main Camera"], 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);
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();
}
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>
);
}
}
+373
View File
@@ -0,0 +1,373 @@
import React, { Component } from "react";
import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
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 Viewer 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();
}
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);
}
}
set_object(path, object) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
// add controls if object is a camera
if (object instanceof THREE.Camera) {
this.state.controls_main = new TrackballControls(
object,
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.staticMoving = false; // false is default
this.state.controls_main.target.set(0, 0, 0); // focus point of the controls
this.state.controls_main.autoRotate = false;
this.state.controls_main.dynamicDampingFactor = 1.0;
this.state.controls_main.update();
// this.send_camera_over_websocket();
// this.state.controls_main.addEventListener("change", () => {
// this.send_camera_over_websocket();
// });
}
}
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);
}
// 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.set_object(["Cameras", "Main Camera"], 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();
}
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>
);
}
}
+22 -25
View File
@@ -1,43 +1,40 @@
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;
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;
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
}
.BackgroundDiv,
.WebRTCVideo {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#BackgroundDiv-video,
#WebRTCVideo-video {
width: 100%;
height: 100%;
object-fit: fill;
width: 100%;
height: 100%;
object-fit: fill;
}
#canvas-container-main {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#canvas-container-main canvas {
position: relative;
height: 100%;
width: 100%;
}
position: relative;
height: 100%;
width: 100%;
}
+105 -105
View File
@@ -11,131 +11,131 @@
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
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}$/
/^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;
}
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`;
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);
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'
);
// 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);
}
});
} 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.'
);
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.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);
});
// 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();
});
// 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."
);
});
} 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);
});
}
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
+1 -1
View File
@@ -2,4 +2,4 @@
// 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';
import "@testing-library/jest-dom/extend-expect";
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,3 +1,3 @@
export function split_path(path_str) {
return path_str.split("/").filter(x => x.length > 0);
return path_str.split("/").filter((x) => x.length > 0);
}
-48
View File
@@ -1,48 +0,0 @@
function createPeerConnection() {
var config = {
sdpSemantics: "unified-plan",
};
// if (document.getElementById('use-stun').checked) {
// config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
// }
let pc = new RTCPeerConnection(config);
// register some listeners to help debugging
pc.addEventListener(
"icegatheringstatechange",
function () {
iceGatheringLog.textContent += " -> " + pc.iceGatheringState;
},
false
);
iceGatheringLog.textContent = pc.iceGatheringState;
pc.addEventListener(
"iceconnectionstatechange",
function () {
iceConnectionLog.textContent += " -> " + pc.iceConnectionState;
},
false
);
iceConnectionLog.textContent = pc.iceConnectionState;
pc.addEventListener(
"signalingstatechange",
function () {
signalingLog.textContent += " -> " + pc.signalingState;
},
false
);
signalingLog.textContent = pc.signalingState;
// connect audio / video
pc.addEventListener("track", function (evt) {
if (evt.track.kind == "video")
document.getElementById("video").srcObject = evt.streams[0];
else document.getElementById("audio").srcObject = evt.streams[0];
});
return pc;
}
+19
View File
@@ -8745,6 +8745,18 @@ text-table@^0.2.0:
resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==
three-wtm@^1.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/three-wtm/-/three-wtm-1.0.2.tgz#f923ba885fc14ec15808670f67f82a0a7139bd64"
integrity sha512-gsjjF9XYHeqsKxCHqN+hhGAKuTqcV9ouw0Ad7SRTdZ65cDjjZkSR5KYcbW7tgwBu16jFagOG9VVjuBbGd40Kbw==
dependencies:
three "^0.133.1"
three@^0.133.1:
version "0.133.1"
resolved "https://registry.yarnpkg.com/three/-/three-0.133.1.tgz#5606f4817d67a09d9212d4ccbd6826564774f8f4"
integrity sha512-WydohO8ll949B0FTD6MGz59Yv2Lwj8hvObg/0Heh2r42S6+tQC1WByfCNRdmG4D7+odfGod+n8JPV1I2xrboWw==
three@^0.142.0:
version "0.142.0"
resolved "https://registry.yarnpkg.com/three/-/three-0.142.0.tgz#89e226a16221f212eb1d40f0786604b711f28aed"
@@ -9527,6 +9539,13 @@ ws@~8.2.3:
resolved "https://registry.yarnpkg.com/ws/-/ws-8.2.3.tgz#63a56456db1b04367d0b721a0b80cae6d8becbba"
integrity sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==
wwobjloader2@^4.0:
version "4.0.1"
resolved "https://registry.yarnpkg.com/wwobjloader2/-/wwobjloader2-4.0.1.tgz#8846325f313b100e6762d09e382398a9ac5a556b"
integrity sha512-+i8jex37jeIcWfTaHLioAvKMcKC/T6yvODVu09FkvKkRsOb843JNjoPxWj5oehedpx2Fj59kK0b7mvO/g4/FXg==
dependencies:
three "^0.133.1"
xml-name-validator@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a"
-25
View File
@@ -1,25 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from . import commands
from . import geometry
from . import visualizer
from . import transformations
from .visualizer import ViewerWindow, Viewer
def viewer_assets_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "viewer"))
+4 -11
View File
@@ -12,24 +12,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info >= (3, 0):
unicode = str
from .geometry import (
Geometry,
Object,
from pyrad.viewer.server.geometry import (
Mesh,
MeshPhongMaterial,
Object,
OrthographicCamera,
PerspectiveCamera,
PointsMaterial,
Points,
PointsMaterial,
)
from .path import Path
from pyrad.viewer.server.path import Path
class SetObject:
+1 -3
View File
@@ -29,15 +29,13 @@ else:
import umsgpack
import numpy as np
from . import transformations as tf
class SceneElement(object):
def __init__(self):
self.uuid = unicode(uuid.uuid1())
def intrinsic_transform(self):
return tf.identity_matrix()
return np.identity(4)
class ReferenceSceneElement(SceneElement):
-2
View File
@@ -29,7 +29,6 @@ import zmq.eventloop.ioloop
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcrtpsender import RTCRtpSender
from zmq.eventloop.zmqstream import ZMQStream
from pyrad.viewer.server.socket import SerializingContext
from pyrad.viewer.server.tree import SceneTree, find_node, walk
from pyrad.viewer.server.video_stream import SingleFrameStreamTrack
@@ -126,7 +125,6 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
class ZMQWebSocketBridge(object):
context = zmq.Context()
# context = SerializingContext()
def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None):
self.host = host
-127
View File
@@ -1,127 +0,0 @@
# https://gist.github.com/jeffbass/ebf877e964c9a0b84272
# zmqimage.py -- classes to send, receive and display cv2 images via zmq
# based on serialization in pyzmq docs and pyzmq/examples/serialization
"""
PURPOSE:
These classes allow a headless (no display) computer running OpenCV code
to display OpenCV images on another computer with a display.
For example, a headless Raspberry Pi with no display can run OpenCV code
and can display OpenCV images on a Mac with a display.
USAGE:
First, start this "display server" program on the computer with a display:
# imageShowServer.py
import zmqimage
zmq = zmqimage.zmqImageShowServer()
print "Starting zmqImageShow Server..."
print " press Ctrl-C to stop"
while True: # Until Ctrl-C is pressed, will repeatedly
zmq.imshow() # display images sent from the headless computer
Run the above program by:
python imageShowServer.py
Leave the above program running in its own terminal window.
Then, run a program like the one below on the headless computer.
In most cases, it will be run using ssh into the headless computer
from another terminal window on the computer with a display.
The python lines below represent a program fragment as an example.
Use zmq.imshow("Image Display Name", image) instead of
cv2.imshow("Image Display Name", image) and the images will
display on the computer running the program above:
import numpy as np
import cv2
import zmqimage
print "Connecting to zmqShowImage Server ... "
zmq = zmqimage.zmqConnect()
image = np.zeros((500, 500), dtype="uint8")
zmq.imshow("Zero Image 500 x 500", image)
# build a rectangular mask & display it
mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(mask, (0, 90), (300, 450), 255, -1)
zmq.imshow("Rectangular Mask", mask)
CAVEATS:
There is no error checking and only Ctrl-C stops the display server.
While zmq.imshow() works like cv2.imshow(), no other
cv2 display functions are implemented.
Uses tcp style sockets; sockets and tcp addresses have
defaults in the classes but may be overridden.
AUTHOR:
Jeff Bass, https://github.com/jeffbass, jeff@yin-yang-ranch.com
"""
import zmq
import numpy as np
import cv2
class SerializingSocket(zmq.Socket):
"""A class with some extra serialization methods
send_array sends numpy arrays with metadata necessary
for reconstructing the array on the other side (dtype,shape).
Also sends array name for display with cv2.show(image).
recv_array receives dict(arrayname,dtype,shape) and an array
and reconstructs the array with the correct shape and array name.
"""
def send_array(self, A, arrayname="NoName", flags=0, copy=True, track=False):
"""send a numpy array with metadata and array name"""
md = dict(
arrayname=arrayname,
dtype=str(A.dtype),
shape=A.shape,
)
self.send_json(md, flags | zmq.SNDMORE)
return self.send(A, flags, copy=copy, track=track)
def recv_array(self, flags=0, copy=True, track=False):
"""recv a numpy array, including arrayname, dtype and shape"""
md = self.recv_json(flags=flags)
msg = self.recv(flags=flags, copy=copy, track=track)
A = np.frombuffer(msg, dtype=md["dtype"])
return (md["arrayname"], A.reshape(md["shape"]))
class SerializingContext(zmq.Context):
_socket_class = SerializingSocket
class zmqConnect:
"""A class that opens a zmq REQ socket on the headless computer"""
def __init__(self, connect_to="tcp://jeff-mac:5555"):
"""initialize zmq socket for sending images to display on remote computer"""
"""connect_to is the tcp address:port of the display computer"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REQ)
self.zmq_socket.connect(connect_to)
def imshow(self, arrayname, array):
"""send image to display on remote server"""
if array.flags["C_CONTIGUOUS"]:
# if array is already contiguous in memory just send it
self.zmq_socket.send_array(array, arrayname, copy=False)
else:
# else make it contiguous before sending
array = np.ascontiguousarray(array)
self.zmq_socket.send_array(array, arrayname, copy=False)
message = self.zmq_socket.recv()
class zmqImageShowServer:
"""A class that opens a zmq REP socket on the display computer to receive images"""
def __init__(self, open_port="tcp://*:5555"):
"""initialize zmq socket on viewing computer that will display images"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REP)
self.zmq_socket.bind(open_port)
def imshow(self, copy=False):
"""receive and show image on viewing computer display"""
arrayname, image = self.zmq_socket.recv_array(copy=False)
# print "Received Array Named: ", arrayname
# print "Array size: ", image.shape
cv2.imshow(arrayname, image)
cv2.waitKey(0)
self.zmq_socket.send(b"OK")
File diff suppressed because it is too large. Load diff
@@ -27,13 +27,13 @@ import torch
import pyrad.viewer.server.cameras as c
import pyrad.viewer.server.geometry as g
import pyrad.viewer.server.transformations as tf
from pyrad.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix
from pyrad.cameras.rays import RayBundle
from pyrad.utils import profiler
from pyrad.utils.config import ViewerConfig
from pyrad.viewer.server import Viewer
from pyrad.viewer.server.visualizer import Viewer
from pyrad.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h
from pyrad.viewer.server.transformations import get_translation_matrix
class CameraChangeException(Exception):
@@ -64,7 +64,6 @@ class VisualizerState:
if self.config.enable:
zmq_url = self.config.zmq_url
self.vis = Viewer(zmq_url=zmq_url)
logging.info("Connected to viewer at %s", zmq_url)
self.vis.delete()
else:
logging.info("Continuing without viewer.")
@@ -123,6 +122,10 @@ class VisualizerState:
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 _async_check_camera_update(self):
"""Async function to check whether camera has been updated in visualizer"""
self.check_done_render = False
@@ -229,7 +232,7 @@ def show_obj(vis, obj_path, name="obj", color=None):
def draw_camera_frustum(
vis,
image=np.random.rand(100, 100, 3) * 255.0,
pose=tf.translation_matrix([0, 0, 0]),
pose=get_translation_matrix([0, 0, 0]),
K=None,
name="0000000",
displayed_focal_length=None,
@@ -268,17 +271,17 @@ def draw_camera_frustum(
g_frustum = c.frustum(scale=1.0, focal_length=displayed_focal_length, width=width, height=height)
vis[name + "/frustum"].set_object(g_frustum)
if not realistic:
vis[name + "/frustum"].set_transform(tf.translation_matrix([0, 0, displayed_focal_length]))
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:
vis[name + "/image_plane"].set_transform(tf.translation_matrix([0, 0, -displayed_focal_length]))
vis[name + "/image_plane"].set_transform(get_translation_matrix([0, 0, -displayed_focal_length]))
if shift_forward:
matrix = tf.translation_matrix([0, 0, displayed_focal_length])
matrix2 = tf.translation_matrix([0, 0, -shift_forward])
matrix = get_translation_matrix([0, 0, displayed_focal_length])
matrix2 = get_translation_matrix([0, 0, -shift_forward])
vis[name + "/frustum"].set_transform(matrix2 @ matrix)
vis[name + "/image_plane"].set_transform(matrix2)
@@ -286,14 +289,7 @@ def draw_camera_frustum(
vis[name].set_transform(pose)
def set_persp_camera(vis, pose, K, colmap=True):
"""Assumes simple pinhole model for intrinsics.
Args:
colmap: whether to use the colmap camera coordinate convention or not
"""
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
def set_persp_intrinsics_matrix(vis, K):
pp_w = K[0, 2]
pp_h = K[1, 2]
assert K[0, 0] == K[1, 1]
@@ -302,9 +298,24 @@ def set_persp_camera(vis, pose, K, colmap=True):
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()
@@ -316,4 +327,4 @@ def draw_aabb(vis, aabb, name="aabb"):
lengths = aabb[1] - aabb[0]
vis[name].set_object(g.Box(lengths.tolist()), material=g.MeshPhongMaterial(color=0xFF0000, opacity=0.1))
center = aabb[0] + lengths / 2.0
vis[name].set_transform(tf.translation_matrix(center.tolist()))
vis[name].set_transform(get_translation_matrix(center.tolist()))
+49 -7
View File
@@ -12,28 +12,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import logging
import signal
import sys
import numpy as np
import msgpack
import msgpack_numpy
import numpy as np
import umsgpack
import zmq
from pyrad.viewer.server.socket import SerializingContext
from .commands import Delete, SetObject, GetObject, SetProperty, SetTransform
from .path import Path
from pyrad.viewer.server.commands import Delete, GetObject, SetObject, SetProperty, SetTransform
from pyrad.viewer.server.path import Path
class ViewerWindow(object):
context = zmq.Context()
# context = SerializingContext()
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()
@@ -46,11 +46,53 @@ class ViewerWindow(object):
)
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...")
response = self.send_ping()
logging.info("Successfully connected.")
signal.alarm(0) # cancel the alarm
except Exception as e:
logging.info(e)
sys.exit()
class Viewer(object):
"""Visualizer class for connecting to the bridge server."""
def __init__(self, zmq_url: str = None, window: ViewerWindow = None):
"""_summary_
Args:
zmq_url (str, optional): _description_. Defaults to None.
window (ViewerWindow, optional): _description_. Defaults to None.
timeout (str, optional): _description_. Defaults to None.
"""
if zmq_url is None and window is None:
raise ValueError("Must specify either zmq_url or window.")
if window is None: