Free Motion Capture for Everyone πβ¨
TypeScript
commit bc its been a sec
jonmatthisd984814f1d9a
diff --git a/bin/build_installer/run_pyinstaller.py b/bin/build_installer/run_pyinstaller.pyindex 6c366595..571a3f59 100644--- a/bin/build_installer/run_pyinstaller.py+++ b/bin/build_installer/run_pyinstaller.py@@ -17,7 +17,7 @@ def run_pyinstaller():print(f"Running PyInstaller with spec file {SPEC_FILE_PATH}...")installer_parameters = [- SPEC_FILE_PATH,+ # SPEC_FILE_PATH,'--log-level', 'INFO']diff --git a/bin/installer.sh b/bin/installer.shindex b6c6dcd3..cea156c7 100755--- a/bin/installer.sh+++ b/bin/installer.sh@@ -1 +1 @@-pyinstaller --name="freemocap" --windowed --onefile .\RUN_ME.py+pyinstaller --name="freemocap" --windowed --onefile .\freemocap\__main__.pydiff --git a/freemocap-ui/src/components/viewport3d/ImageMesh.tsx b/freemocap-ui/src/components/viewport3d/ImageMesh.tsxindex 40906c2d..a6827c35 100644--- a/freemocap-ui/src/components/viewport3d/ImageMesh.tsx+++ b/freemocap-ui/src/components/viewport3d/ImageMesh.tsx@@ -31,8 +31,11 @@ export const ImageMesh: React.FC<ImageMeshProps> = ({imageUrl, position}) => {camera.far = Math.max(imageWidth, imageHeight);const helper = new THREE.CameraHelper(camera);scene.add(helper);- meshRef.current.material.map = texture;- meshRef.current.material.needsUpdate = true;++ if (mesh.material instanceof THREE.MeshBasicMaterial) {+ mesh.material.map = texture;+ mesh.material.needsUpdate = true;+ }}}, [texture]);diff --git a/freemocap-ui/src/views/Config.tsx b/freemocap-ui/src/views/Config.tsxindex 3b3d1be2..414d79a3 100644--- a/freemocap-ui/src/views/Config.tsx+++ b/freemocap-ui/src/views/Config.tsx@@ -8,6 +8,8 @@ export const ConfigView = () => {const [devices, setDevices] = React.useState<MediaDeviceInfo[]>([]);const { latestSkellyCamAppState } = useWebSocketContext();++useAsync(async () => {const cam = new AvailableCameraDevices();const deviceInfos = await cam.findAllCameras(false);@@ -16,14 +18,15 @@ export const ConfigView = () => {const devicesWithNames = devices.filter(x => x.label);+return (<Box>- <Typography>JS Detected Cameras</Typography>+ <h2>JS Detected Cameras</h2>{devicesWithNames.map(device => (<Typography key={device.deviceId}>Webcam {device.label}</Typography>))}-- <Typography>Latest SkellyCamAppState</Typography>+ <br/>+ <h2>Latest SkellyCamAppState</h2>{latestSkellyCamAppState && (<Typography component="pre">{JSON.stringify(latestSkellyCamAppState, null, 2)}diff --git a/freemocap/api/http/ui/ui.html b/freemocap/api/http/ui/ui.htmldeleted file mode 100644index d08cfe59..00000000--- a/freemocap/api/http/ui/ui.html+++ /dev/null@@ -1,288 +0,0 @@-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="UTF-8">- <meta content="width=device-width, initial-scale=1.0" name="viewport">- <title>FreeMoCap UI Tester</title>- <style>- body {- margin: 0;- font-family: Arial, sans-serif;- display: flex;- flex-direction: column;- height: 100vh;- overflow: hidden;- background-color: #f4f4f9;- }-- h1 {- font-size: 24px;- background-color: #4a4e69;- color: white;- margin: 0;- padding: 10px;- text-align: center;- }-- #controls {- display: flex;- align-items: center;- background-color: #4a4e69;- padding: 10px;- color: white;- justify-content: center;- }-- #ws-status {- margin-right: 15px;- font-weight: bold;- }-- button {- margin: 0 10px;- padding: 10px;- font-size: small;- background-color: #9a8c98;- color: white;- border: none;- border-radius: 5px;- cursor: pointer;- transition: background-color 0.3s;- }-- button:hover {- background-color: #c9ada7;- }-- #content-container {- display: flex;- flex-grow: 1;- overflow: hidden;- position: relative;- }-- #images-container {- flex: 1;- display: flex;- flex-wrap: wrap;- overflow-y: auto;- background-color: #22223b;- justify-content: center;- align-items: center;- padding: 10px;- }-- .image {- max-width: 100%;- height: auto;- margin: 5px;- }-- #threejs-container {- position: absolute;- top: 20px;- right: 20px;- width: 20%;- height: 20%;- background-color: rgba(0, 0, 0, 0.5);- border-radius: 8px;- overflow: hidden;- cursor: grab;- }-- #log-container {- height: 100px;- overflow-y: auto;- background-color: #4a4e69;- color: white;- padding: 10px;- }-- .log-entry {- margin-bottom: 5px;- }- </style>- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>- <script>- let ws;- let isConnected = false;- const websocket_url = '{{WEBSOCKET_URL}}/websocket/connect';- const http_url = '{{HTTP_URL}}';- const imageElements = {};- const spheres = {};- let scene;- let isDragging = false;- let dragStartX, dragStartY;- let initialX, initialY;-- function updateStatus() {- document.getElementById('ws-status').innerText = isConnected ? 'Status: Connected βοΈ' : 'Status: Disconnected β';- document.getElementById('ws-status').style.color = isConnected ? '#4caf50' : '#f44336';- }-- function connectWebSocket() {- ws = new WebSocket(websocket_url);- const decoder = new TextDecoder('utf-8');-- ws.onopen = () => {- isConnected = true;- updateStatus();- };- ws.onclose = () => {- isConnected = false;- updateStatus();- };- ws.onmessage = async (event) => {- if (event.data instanceof Blob) {- const arrayBuffer = await event.data.arrayBuffer();- const jsonString = decoder.decode(arrayBuffer);- const data = JSON.parse(jsonString);- addLogEntry(`Received message with length: ${jsonString.length} from mf_payload# ${data.multi_frame_number}`);- updateImages(data.jpeg_images);- updateSpheres(data.latest_pipeline_output?.aggregation_layer_output?.points3d);- }- };- }-- function updateSpheres(points3d) {- if (!points3d) return;-- for (const id in spheres) {- spheres[id].updated = false;- }-- for (const [point_id, coords] of Object.entries(points3d)) {- if (!spheres[point_id]) {- const geometry = new THREE.SphereGeometry(1, 10, 10);- const material = new THREE.MeshBasicMaterial({color: 0xff0000});- const sphere = new THREE.Mesh(geometry, material);- scene.add(sphere);- spheres[point_id] = {mesh: sphere, updated: true};- } else {- spheres[point_id].mesh.position.set(coords[0], coords[1], coords[2]);- spheres[point_id].updated = true;- }- }-- for (const id in spheres) {- spheres[id].mesh.visible = spheres[id].updated;- }- }-- function updateImages(images) {- const container = document.getElementById('images-container');- for (const cameraId in images) {- if (!imageElements[cameraId]) {- const img = document.createElement('img');- img.className = 'image';- container.appendChild(img);- imageElements[cameraId] = img;- }- if (images[cameraId]) {- imageElements[cameraId].src = 'data:image/jpeg;base64,' + images[cameraId];- }- }- }-- function addLogEntry(entry) {- const logContainer = document.getElementById('log-container');- const logEntry = document.createElement('div');- logEntry.className = 'log-entry';- logEntry.innerText = entry;- logContainer.prepend(logEntry);-- if (logContainer.children.length > 30) {- logContainer.removeChild(logContainer.lastChild);- }- }-- async function callApi(endpoint, method = 'GET') {- try {- const response = await fetch(endpoint, {method});- const data = await response.json();- document.getElementById('result').innerText = JSON.stringify(data, null, 2);- addLogEntry(`Success: ${endpoint} - ${JSON.stringify(data)}`);- } catch (error) {- document.getElementById('result').innerText = `Error: ${error.message}`;- addLogEntry(`Error: ${endpoint} - ${error.message}`);- }- }-- function initThreeJS() {- const container = document.getElementById('threejs-container');- scene = new THREE.Scene();- const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);- const renderer = new THREE.WebGLRenderer();- renderer.setSize(container.clientWidth, container.clientHeight);- container.appendChild(renderer.domElement);-- const axesHelper = new THREE.AxesHelper(5);- scene.add(axesHelper);-- const gridHelper = new THREE.GridHelper(10, 10);- scene.add(gridHelper);-- camera.position.y = 5;- camera.position.z = 25;-- const light = new THREE.DirectionalLight(0xffffff, 1);- light.position.set(1, 1, 1).normalize();- scene.add(light);-- function animate() {- requestAnimationFrame(animate);- renderer.render(scene, camera);- }-- animate();-- // Add event listeners for dragging- container.addEventListener('mousedown', onMouseDown);- document.addEventListener('mousemove', onMouseMove);- document.addEventListener('mouseup', onMouseUp);- }-- function onMouseDown(event) {- isDragging = true;- dragStartX = event.clientX;- dragStartY = event.clientY;- const rect = event.target.getBoundingClientRect();- initialX = rect.left;- initialY = rect.top;- event.target.style.cursor = 'grabbing';- }-- function onMouseMove(event) {- if (isDragging) {- const dx = event.clientX - dragStartX;- const dy = event.clientY - dragStartY;- const container = document.getElementById('threejs-container');- container.style.left = `${initialX + dx}px`;- container.style.top = `${initialY + dy}px`;- }- }-- function onMouseUp(event) {- isDragging = false;- event.target.style.cursor = 'grab';- }-- window.onload = initThreeJS;- window.onload = connectWebSocket;- </script>-</head>-<body>- <h1>FreeMoCap Test UI</h1>- <div id="controls">- <span id="ws-status">Status: Disconnected β</span>- <button onclick="connectWebSocket()">Connect WebSocket</button>- <button onclick="callApi(`${http_url}/skellycam/cameras/connect/detect`)">Connect to Cameras</button>- </div>- <div id="content-container">- <div id="images-container"></div>- <div id="threejs-container"></div>- </div>- <h3>Logs</h3>- <div id="log-container"></div>-</body>-</html>\ No newline at end of filediff --git a/freemocap/api/http/ui/ui_router.py b/freemocap/api/http/ui/ui_router.pydeleted file mode 100644index f77d7557..00000000--- a/freemocap/api/http/ui/ui_router.py+++ /dev/null@@ -1,28 +0,0 @@-import logging-import os--from fastapi import APIRouter-from starlette.responses import HTMLResponse--from freemocap.api.server.server_constants import PORT, APP_URL--logger = logging.getLogger(__name__)--ui_router = APIRouter()---@ui_router.get("/", response_class=HTMLResponse)-def serve_ui():- logger.info("Serving UI HTML to `/ui`")- file_path = os.path.join(os.path.dirname(__file__), 'ui.html')- with open(file_path, 'r', encoding='utf-8') as file:- ui_html_string = file.read()- ui_html_string = ui_html_string.replace("{{HTTP_URL}}", APP_URL)- ui_html_string = ui_html_string.replace("{{WEBSOCKET_URL}}", APP_URL.replace("http", "ws"))- return HTMLResponse(content=ui_html_string, status_code=200)---if __name__ == "__main__":- import uvicorn-- uvicorn.run(ui_router, host="localhost", port=PORT)diff --git a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.pyindex 31414357..d5f3a8de 100644--- a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py+++ b/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py@@ -125,7 +125,7 @@ class CalibrationAggregationProcessNode(BaseAggregationNode):for camera_id in input_queues.keys()}if multi_camera_calibrator.has_calibration:- for camera_id, transform in multi_camera_calibrator.multi_camera_calibration_estimate.camera_extrinsic_transforms_by_camera_id.items():+ for camera_id, transform in multi_camera_calibrator.multi_camera_calibration_estimate.camera_transforms_by_camera_id.items():points3d[f"camera-{camera_id}"] = transform.translation_vector.vectoroutput = CalibrationPipelineOutputData(diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py b/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.pyindex db206e55..c9641eda 100644--- a/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py+++ b/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py@@ -17,11 +17,8 @@ from freemocap.pipelines.calibration_pipeline.camera_math_models import Transforclass MultiCameraCalibrationEstimate(BaseModel):principal_camera_id: CameraId- camera_extrinsic_transforms_by_camera_id: dict[CameraId, TransformationMatrix]+ camera_transforms_by_camera_id: dict[CameraId, TransformationMatrix]- def to_list(self):- return [transform.extrinsics_matrix.flatten() for transform in- self.camera_extrinsic_transforms_by_camera_id.values()]class MultiCameraCalibrator(BaseModel):@@ -135,6 +132,10 @@ class MultiCameraCalibrator(BaseModel):camera_transforms[camera_id] = TransformationMatrix.from_extrinsics(extrinsics_matrix=np.array(optimization_result[starting_index:ending_index]).reshape(3, 4),reference_frame=f"camera-{self.principal_camera_id}")+ self.multi_camera_calibration_estimate = MultiCameraCalibrationEstimate(+ principal_camera_id=self.principal_camera_id,+ camera_transforms_by_camera_id=camera_transforms+ )def _calculate_camera_to_principal_camera_transforms(self, camera_pair_secondary_camera_transform_estimates) -> \dict[CameraId, TransformationMatrix]:@@ -203,6 +204,10 @@ if __name__ == "__main__":loaded: MultiCameraCalibrator = pickle.load(open(pickle_path, "rb"))loaded.run_multi_camera_optimization()- # save out+ ## save out state in debug console to re-run w/o camera streams+ # import pickle+ # from pathlib import Path+ #+ # pickle_path = r"C:\Users\jonma\github_repos\freemocap_organization\freemocap\freemocap\saved_mc_calib.pkl"# with open(pickle_path, "wb") as f:# pickle.dump(self, f)