Add time controls to viewer (#1764)

This commit is contained in:
Matthew Tancik authored and GitHub committed 2023-04-18 15:06:03 -07:00
1 parent ea14152ae6
commit b7fd273638
15 files changed
+280 -15

No files matched your search

@@ -179,6 +179,7 @@ class DataManager(nn.Module):
eval_count (int): the step number of our eval iteration, needs to be incremented manually
train_dataset (Dataset): the dataset for the train dataset
eval_dataset (Dataset): the dataset for the eval dataset
includes_time (bool): whether the dataset includes time information
Additional attributes specific to each subclass are defined in the setup_train and setup_eval
functions.
@@ -189,6 +190,7 @@ class DataManager(nn.Module):
eval_dataset: Optional[Dataset] = None
train_sampler: Optional[DistributedSampler] = None
eval_sampler: Optional[DistributedSampler] = None
includes_time: bool = False
def __init__(self):
"""Constructor for the DataManager class.
@@ -407,6 +409,7 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
else:
self.config.data = self.config.dataparser.data
self.dataparser = self.dataparser_config.setup()
self.includes_time = self.dataparser.includes_time
self.train_dataparser_outputs = self.dataparser.get_dataparser_outputs(split="train")
self.train_dataset = self.create_train_dataset()
@@ -127,9 +127,14 @@ class DataParser:
Args:
config: datasetparser config containing all information needed to instantiate dataset
Attributes:
config: datasetparser config containing all information needed to instantiate dataset
includes_time: Does the dataset include time information in the camera poses.
"""
config: DataParserConfig
includes_time: bool = False
def __init__(self, config: DataParserConfig):
super().__init__()
@@ -53,6 +53,7 @@ class DNeRF(DataParser):
"""DNeRF Dataset"""
config: DNeRFDataParserConfig
includes_time: bool = True
def __init__(self, config: DNeRFDataParserConfig):
super().__init__(config=config)
@@ -202,6 +202,7 @@ class Dycheck(DataParser):
"""Dycheck (https://arxiv.org/abs/2210.13445) Dataset `iphone` subset"""
config: DycheckDataParserConfig
includes_time: bool = True
def __init__(self, config: DycheckDataParserConfig):
super().__init__(config=config)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "viewer",
"homepage": ".",
"version": "23-04-10-0",
"version": "23-04-18-0",
"private": true,
"dependencies": {
"@emotion/react": "^11.10.4",
@@ -48,6 +48,7 @@ import { get_curve_object_from_cameras, get_transform_matrix } from './curve';
import {
ViserWebSocketContext,
sendWebsocketMessage,
makeThrottledMessageSender,
} from '../../WebSocket/ViserWebSocket';
import RenderModal from '../../RenderModal';
import LoadPathModal from '../../LoadPathModal';
@@ -65,6 +66,100 @@ function set_camera_position(camera, matrix) {
mat.decompose(camera.position, camera.quaternion, camera.scale);
}
function RenderTimeSelector(props) {
const throttled_time_message_sender = props.throttled_time_message_sender;
const disabled = props.disabled;
const isGlobal = props.isGlobal;
const camera = props.camera;
const globalRenderTime = props.globalRenderTime;
const setGlobalRenderTime = props.setGlobalRenderTime;
const applyAll = props.applyAll;
const setAllCameraRenderTime = props.setAllCameraRenderTime;
const getRenderTimeLabel = () => {
if (!isGlobal) {
return camera.renderTime;
}
camera.renderTime = globalRenderTime;
return globalRenderTime;
};
const [UIRenderTime, setUIRenderTime] = React.useState(
isGlobal ? globalRenderTime : getRenderTimeLabel(),
);
const [valid, setValid] = React.useState(true);
useEffect(() => {
setUIRenderTime(getRenderTimeLabel());
throttled_time_message_sender({
type: 'TimeConditionMessage',
time: camera.renderTime,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [camera, globalRenderTime]);
const setRndrTime = (val) => {
if (!isGlobal) {
camera.renderTime = val;
} else {
camera.renderTime = val;
setGlobalRenderTime(val);
}
if (applyAll) {
setAllCameraRenderTime(val);
}
throttled_time_message_sender({
type: 'TimeConditionMessage',
time: camera.renderTime,
});
};
const handleValidation = (e) => {
const valueFloat = parseFloat(e.target.value);
let valueStr = String(valueFloat);
if (e.target.value >= 0 && e.target.value <= 1) {
setValid(true);
if (valueFloat === 1.0) {
valueStr = '1.0';
}
if (valueFloat === 0.0) {
valueStr = '0.0';
}
setUIRenderTime(parseFloat(valueStr));
setRndrTime(parseFloat(valueStr));
} else {
setValid(false);
}
};
return (
<TextField
label="Render Time"
InputLabelProps={{
style: { color: '#8E8E8E' },
}}
inputProps={{
inputMode: 'numeric',
}}
onChange={(e) => setUIRenderTime(e.target.value)}
onBlur={(e) => handleValidation(e)}
disabled={disabled}
sx={{
input: {
WebkitTextFillColor: `${disabled ? '#24B6FF' : '#EBEBEB'} !important`,
color: `${disabled ? '#24B6FF' : '#EBEBEB'} !important`,
},
}}
value={UIRenderTime}
error={!valid}
helperText={!valid ? 'RenderTime should be between 0.0 and 1.0' : ''}
variant="standard"
/>
);
}
function FovSelector(props) {
const fovLabel = props.fovLabel;
const setFovLabel = props.setFovLabel;
@@ -200,6 +295,7 @@ function FovSelector(props) {
}
function CameraList(props) {
const throttled_time_message_sender = props.throttled_time_message_sender;
const sceneTree = props.sceneTree;
const cameras = props.cameras;
const camera_main = props.camera_main;
@@ -211,7 +307,6 @@ function CameraList(props) {
const cameraProperties = props.cameraProperties;
const setCameraProperties = props.setCameraProperties;
const isAnimated = props.isAnimated;
const dispatch = props.dispatch;
// eslint-disable-next-line no-unused-vars
const slider_value = props.slider_value;
const set_slider_value = props.set_slider_value;
@@ -411,13 +506,19 @@ function CameraList(props) {
fovLabel={fovLabel}
setFovLabel={setFovLabel}
camera={camera}
dispatch={dispatch}
disabled={!isAnimated('FOV')}
isGlobal={false}
changeMain={false}
/>
)}
{!isAnimated('FOV') && (
{isAnimated('RenderTime') && (
<RenderTimeSelector
throttled_time_message_sender={throttled_time_message_sender}
camera={camera}
disabled={!isAnimated('RenderTime')}
isGlobal={false}
/>
)}
{!isAnimated('FOV') && !isAnimated('RenderTime') && (
<p style={{ fontSize: 'smaller', color: '#999999' }}>
Animated camera properties will show up here!
</p>
@@ -455,7 +556,10 @@ export default function CameraPanel(props) {
);
const viser_websocket = useContext(ViserWebSocketContext);
const throttled_time_message_sender =
makeThrottledMessageSender(viser_websocket);
const DEFAULT_FOV = 50;
const DEFAULT_RENDER_TIME = 0.0;
// react state
const [cameras, setCameras] = React.useState([]);
@@ -471,6 +575,8 @@ export default function CameraPanel(props) {
const [load_path_modal_open, setLoadPathModalOpen] = React.useState(false);
const [animate, setAnimate] = React.useState(new Set());
const [globalFov, setGlobalFov] = React.useState(DEFAULT_FOV);
const [globalRenderTime, setGlobalRenderTime] =
React.useState(DEFAULT_RENDER_TIME);
// leva store
const cameraPropsStore = useCreateStore();
@@ -506,6 +612,10 @@ export default function CameraPanel(props) {
const crop_center = useSelector((state) => state.renderingState.crop_center);
const crop_scale = useSelector((state) => state.renderingState.crop_scale);
const display_render_time = useSelector(
(state) => state.renderingState.use_time_conditioning,
);
const setRenderHeight = (value) => {
dispatch({
type: 'write',
@@ -561,7 +671,7 @@ export default function CameraPanel(props) {
const camera_main_copy = camera_main.clone();
camera_main_copy.aspect = 1.0;
camera_main_copy.fov = globalFov;
camera_main_copy.renderTime = 0.0;
camera_main_copy.renderTime = globalRenderTime;
const new_camera_properties = new Map();
camera_main_copy.properties = new_camera_properties;
new_camera_properties.set('FOV', globalFov);
@@ -800,14 +910,18 @@ export default function CameraPanel(props) {
let lookat = null;
let up = null;
let fov = null;
let render_time = null;
position = curve_object.curve_positions.getPoint(point);
lookat = curve_object.curve_lookats.getPoint(point);
up = curve_object.curve_ups.getPoint(point);
fov = curve_object.curve_fovs.getPoint(point).z;
render_time = curve_object.curve_render_times.getPoint(point).z;
render_time = Math.max(Math.min(render_time, 1.0), 0.0); // clamp time values to [0, 1]
const mat = get_transform_matrix(position, lookat, up);
set_camera_position(camera_render, mat);
setFieldOfView(fov);
setGlobalFov(fov);
setGlobalRenderTime(render_time);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [slider_value, render_height, render_width]);
@@ -847,11 +961,21 @@ export default function CameraPanel(props) {
const mat = get_transform_matrix(position, lookat, up);
camera_path.push({
camera_to_world: mat.transpose().elements, // convert from col-major to row-major matrix
fov,
aspect: camera_render.aspect,
});
if (display_render_time) {
const renderTime = curve_object.curve_render_times.getPoint(pt).z;
camera_path.push({
camera_to_world: mat.transpose().elements, // convert from col-major to row-major matrix
fov,
aspect: camera_render.aspect,
render_time: Math.max(Math.min(renderTime, 1.0), 0.0), // clamp time values to [0, 1]
});
} else {
camera_path.push({
camera_to_world: mat.transpose().elements, // convert from col-major to row-major matrix
fov,
aspect: camera_render.aspect,
});
}
}
const keyframes = [];
@@ -1026,6 +1150,12 @@ export default function CameraPanel(props) {
}
};
const setAllCameraRenderTime = (val) => {
for (let i = 0; i < cameras.length; i += 1) {
cameras[i].renderTime = val;
}
};
return (
<div className="CameraPanel">
<div>
@@ -1090,6 +1220,52 @@ export default function CameraPanel(props) {
/>
</LevaStoreProvider>
</div>
{display_render_time && (
<div className="CameraList-row-animation-properties">
<Tooltip title="Animate Render Time for Each Camera">
<Button
value="animateRenderTime"
selected={isAnimated('RenderTime')}
onClick={() => {
toggleAnimate('RenderTime');
}}
style={{
maxWidth: '20px',
maxHeight: '20px',
minWidth: '20px',
minHeight: '20px',
position: 'relative',
top: '22px',
}}
sx={{
mt: 1,
}}
>
<Animation
style={{
color: isAnimated('RenderTime') ? '#24B6FF' : '#EBEBEB',
maxWidth: '20px',
maxHeight: '20px',
minWidth: '20px',
minHeight: '20px',
}}
/>
</Button>
</Tooltip>
<RenderTimeSelector
throttled_time_message_sender={throttled_time_message_sender}
disabled={false}
isGlobal
camera={camera_main}
dispatch={dispatch}
globalRenderTime={globalRenderTime}
setGlobalRenderTime={setGlobalRenderTime}
applyAll={!isAnimated('RenderTime')}
setAllCameraRenderTime={setAllCameraRenderTime}
changeMain
/>
</div>
)}
{camera_type !== 'equirectangular' && (
<div className="CameraList-row-animation-properties">
<Tooltip title="Animate FOV for Each Camera">
@@ -1345,6 +1521,7 @@ export default function CameraPanel(props) {
</div>
<div className="CameraList-container">
<CameraList
throttled_time_message_sender={throttled_time_message_sender}
sceneTree={sceneTree}
transform_controls={transform_controls}
camera_main={camera_render}
@@ -109,6 +109,13 @@ interface StatusMessage {
interface SaveCheckpointMessage {
type: 'SaveCheckpointMessage';
}
interface UseTimeConditioningMessage {
type: 'UseTimeConditioningMessage';
}
interface TimeConditionMessage {
type: 'TimeConditionMessage';
time: number;
}
export type Message =
| BackgroundImageMessage
@@ -128,4 +135,6 @@ export type Message =
| CameraPathsMessage
| CropParamsMessage
| StatusMessage
| SaveCheckpointMessage;
| SaveCheckpointMessage
| UseTimeConditioningMessage
| TimeConditionMessage;
@@ -258,6 +258,24 @@ function handleMessage(
});
break;
}
// Handle time conditioning messages.
case 'UseTimeConditioningMessage': {
console.log('HERERERE');
dispatch({
type: 'write',
path: 'renderingState/use_time_conditioning',
data: true,
});
break;
}
case 'TimeConditionMessage': {
dispatch({
type: 'write',
path: 'renderingState/time_condition',
data: message.time,
});
break;
}
default: {
console.log('Received message did not match any known types:', message);
break;
+3
View File
@@ -55,6 +55,9 @@ const initialState = {
crop_bg_color: { r: 38, g: 42, b: 55 },
crop_scale: [2.0, 2.0, 2.0],
crop_center: [0.0, 0.0, 0.0],
// Time options
use_time_conditioning: false,
},
// the scene state
sceneState: {
+18 -1
View File
@@ -35,12 +35,14 @@ class ControlPanel:
"""
Initializes the control panel with all the elements
Args:
time_enabled: whether or not the time slider should be enabled
rerender_cb: a callback that will be called when the user changes a parameter that requires a rerender
(eg train speed, max res, etc)
crop_update_cb: a callback that will be called when the user changes the crop parameters
update_output_cb: a callback that will be called when the user changes the output render
"""
def __init__(self, rerender_cb: Callable, crop_update_cb: Callable, update_output_cb: Callable):
def __init__(self, time_enabled: bool, rerender_cb: Callable, crop_update_cb: Callable, update_output_cb: Callable):
# elements holds a mapping from tag: [elements]
self._elements_by_tag: DefaultDict[str, List[ViewerElement]] = defaultdict(lambda: [])
@@ -68,6 +70,8 @@ class ControlPanel:
self._background_color = ViewerRGB("| Background color", (38, 42, 55), cb_hook=crop_update_cb)
self._crop_min = ViewerVec3("| Crop Min", (-1, -1, -1), 0.05, cb_hook=crop_update_cb)
self._crop_max = ViewerVec3("| Crop Max", (1, 1, 1), 0.05, cb_hook=crop_update_cb)
self._time = ViewerSlider("Time", 0.0, 0.0, 1.0, 0.01, cb_hook=rerender_cb)
self._time_enabled = time_enabled
self.add_element(self._train_speed)
self.add_element(self._output_render)
@@ -86,6 +90,8 @@ class ControlPanel:
self.add_element(self._crop_min, additional_tags=("crop",))
self.add_element(self._crop_max, additional_tags=("crop",))
self.add_element(self._time, additional_tags=("time",))
def _train_speed_cb(self) -> None:
"""Callback for when the train speed is changed"""
if self.train_speed == "Fast":
@@ -135,6 +141,7 @@ class ControlPanel:
e.set_hidden(self.output_render == "rgb")
for e in self._elements_by_tag["crop"]:
e.set_hidden(not self.crop_viewport)
self._time.set_hidden(not self._time_enabled)
def update_colormap_options(self, dimensions: int, dtype: type) -> None:
"""update the colormap options based on the current render
@@ -235,3 +242,13 @@ class ControlPanel:
def background_color(self, value: Tuple[int, int, int]):
"""Sets the background color"""
self._background_color.value = value
@property
def time(self) -> float:
"""Returns the current background color"""
return self._time.value
@time.setter
def time(self, value: float):
"""Sets the background color"""
self._time.value = value
@@ -155,7 +155,7 @@ class RenderStateMachine(threading.Thread):
cy=intrinsics_matrix[1, 2],
camera_type=camera_type,
camera_to_worlds=camera_to_world[None, ...],
times=torch.tensor([0.0]),
times=torch.tensor([self.viewer.control_panel.time], dtype=torch.float32),
)
camera = camera.to(self.viewer.get_model().device)
+14 -1
View File
@@ -51,6 +51,7 @@ from nerfstudio.viewer.viser.messages import (
IsTrainingMessage,
NerfstudioMessage,
SaveCheckpointMessage,
TimeConditionMessage,
)
if TYPE_CHECKING:
@@ -110,6 +111,8 @@ class ViewerState:
CONSOLE.print(Panel(table, title="[bold][yellow]Viewer[/bold]", expand=False))
self.include_time = self.pipeline.datamanager.includes_time
# viewer specific variables
self.prev_moving = False
self.output_type_changed = True
@@ -130,8 +133,13 @@ class ViewerState:
self.viser_server.register_handler(CameraPathOptionsRequest, self._handle_camera_path_option_request)
self.viser_server.register_handler(CameraPathPayloadMessage, self._handle_camera_path_payload)
self.viser_server.register_handler(CropParamsMessage, self._handle_crop_params_message)
if self.include_time:
self.viser_server.use_time_conditioning()
self.viser_server.register_handler(TimeConditionMessage, self._handle_time_condition_message)
self.control_panel = ControlPanel(self._interrupt_render, self._crop_params_update, self._output_type_change)
self.control_panel = ControlPanel(
self.include_time, self._interrupt_render, self._crop_params_update, self._output_type_change
)
self.control_panel.install(self.viser_server)
def nested_folder_install(folder_labels: List[str], element: ViewerElement):
@@ -233,6 +241,11 @@ class ViewerState:
self.control_panel.crop_min = tuple(crop_min.tolist())
self.control_panel.crop_max = tuple(crop_max.tolist())
def _handle_time_condition_message(self, message: NerfstudioMessage) -> None:
"""Handle time conditioning message from viewer."""
assert isinstance(message, TimeConditionMessage)
self.control_panel.time = message.time
@property
def is_training(self) -> bool:
"""Get is_training flag from viewer."""
+4
View File
@@ -532,6 +532,10 @@ class MessageApi(abc.ABC):
)
return GuiHandle(handle_state)
def use_time_conditioning(self) -> None:
"""Use time conditioning."""
self._queue(messages.UseTimeConditioningMessage())
def _handle_gui_updates(
self: MessageApi,
client_id: ClientId,
+13
View File
@@ -228,3 +228,16 @@ class StatusMessage(NerfstudioMessage):
@dataclasses.dataclass
class SaveCheckpointMessage(NerfstudioMessage):
"""Save checkpoint message."""
@dataclasses.dataclass
class UseTimeConditioningMessage(NerfstudioMessage):
"""Use time conditioning message."""
@dataclasses.dataclass
class TimeConditionMessage(NerfstudioMessage):
"""Time conditioning message."""
time: float
""" Time conditioning value """
+1
View File
@@ -144,6 +144,7 @@ disable = [
"too-many-branches",
"too-many-instance-attributes",
"too-many-locals",
"too-many-statements",
"unnecessary-ellipsis",
]