mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-28 12:00:02 +08:00
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:
1 parent
966374474d
commit
73fedc7593
67 files changed
+2510
-14057
No files matched your search
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,
|
||||
};
|
||||
Reference in new issue
Block a user