From 215f3b9f44eaacbee83973f57581d31c3931f2c4 Mon Sep 17 00:00:00 2001 From: Butterscotch! Date: Wed, 1 Jun 2022 09:59:17 -0400 Subject: [PATCH] Implement AutoBone into the protocol (#187) Implement event-based AutoBoneHandler & more --- solarxr-protocol | 2 +- src/main/java/dev/slimevr/VRServer.java | 7 + .../java/dev/slimevr/autobone/AutoBone.java | 13 +- .../dev/slimevr/autobone/AutoBoneHandler.java | 402 +++++++++++++++ .../slimevr/autobone/AutoBoneListener.java | 26 + .../slimevr/autobone/AutoBoneProcessType.java | 31 ++ .../java/dev/slimevr/gui/AutoBoneWindow.java | 459 ++++-------------- .../slimevr/poserecorder/PoseRecorder.java | 55 ++- .../slimevr/protocol/ConnectionContext.java | 9 + .../java/dev/slimevr/protocol/RPCHandler.java | 122 ++++- .../dev/slimevr/serial/SerialHandler.java | 4 +- 11 files changed, 758 insertions(+), 372 deletions(-) create mode 100644 src/main/java/dev/slimevr/autobone/AutoBoneHandler.java create mode 100644 src/main/java/dev/slimevr/autobone/AutoBoneListener.java create mode 100644 src/main/java/dev/slimevr/autobone/AutoBoneProcessType.java diff --git a/solarxr-protocol b/solarxr-protocol index 88d9f7060..80f0c5228 160000 --- a/solarxr-protocol +++ b/solarxr-protocol @@ -1 +1 @@ -Subproject commit 88d9f7060cdf4c28210fa0138359adf5b768e9fc +Subproject commit 80f0c5228cdf0a3e67cb7136adfd62a24002d35f diff --git a/src/main/java/dev/slimevr/VRServer.java b/src/main/java/dev/slimevr/VRServer.java index bf3c26e16..775e3edbc 100644 --- a/src/main/java/dev/slimevr/VRServer.java +++ b/src/main/java/dev/slimevr/VRServer.java @@ -27,6 +27,7 @@ import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Consumer; +import dev.slimevr.autobone.AutoBoneHandler; public class VRServer extends Thread { @@ -44,6 +45,7 @@ public class VRServer extends Thread { private final List shareTrackers; private final BVHRecorder bvhRecorder; private final SerialHandler serialHandler; + private final AutoBoneHandler autoBoneHandler; private final ProtocolAPI protocolAPI; private final String configPath; @@ -57,6 +59,7 @@ public class VRServer extends Thread { loadConfig(); serialHandler = new SerialHandler(); + autoBoneHandler = new AutoBoneHandler(this); protocolAPI = new ProtocolAPI(this); hmdTracker = new HMDTracker("HMD"); @@ -356,6 +359,10 @@ public class VRServer extends Thread { return this.serialHandler; } + public AutoBoneHandler getAutoBoneHandler() { + return this.autoBoneHandler; + } + public ProtocolAPI getProtocolAPI() { return protocolAPI; } diff --git a/src/main/java/dev/slimevr/autobone/AutoBone.java b/src/main/java/dev/slimevr/autobone/AutoBone.java index 9ca7e08d2..ba845dfdb 100644 --- a/src/main/java/dev/slimevr/autobone/AutoBone.java +++ b/src/main/java/dev/slimevr/autobone/AutoBone.java @@ -530,7 +530,7 @@ public class AutoBone { LogManager.info("[AutoBone] Epoch " + (epoch + 1) + " average error: " + avgError); if (epochCallback != null) { - epochCallback.accept(new Epoch(epoch + 1, avgError)); + epochCallback.accept(new Epoch(epoch + 1, numEpochs, avgError, configs)); } } @@ -882,11 +882,20 @@ public class AutoBone { public class Epoch { public final int epoch; + public final int totalEpochs; public final float epochError; + public final EnumMap configValues; - public Epoch(int epoch, float epochError) { + public Epoch( + int epoch, + int totalEpochs, + float epochError, + EnumMap configValues + ) { this.epoch = epoch; + this.totalEpochs = totalEpochs; this.epochError = epochError; + this.configValues = configValues; } @Override diff --git a/src/main/java/dev/slimevr/autobone/AutoBoneHandler.java b/src/main/java/dev/slimevr/autobone/AutoBoneHandler.java new file mode 100644 index 000000000..d2692ab6a --- /dev/null +++ b/src/main/java/dev/slimevr/autobone/AutoBoneHandler.java @@ -0,0 +1,402 @@ +package dev.slimevr.autobone; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Future; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.commons.lang3.tuple.Pair; + +import dev.slimevr.VRServer; +import dev.slimevr.poserecorder.PoseFrames; +import dev.slimevr.poserecorder.PoseRecorder; +import dev.slimevr.vr.processor.skeleton.SkeletonConfigValue; +import io.eiren.util.StringUtils; +import io.eiren.util.collections.FastList; +import io.eiren.util.logging.LogManager; + + +public class AutoBoneHandler { + + private final VRServer server; + private final PoseRecorder poseRecorder; + private final AutoBone autoBone; + + private ReentrantLock recordingLock = new ReentrantLock(); + private Thread recordingThread = null; + + private ReentrantLock saveRecordingLock = new ReentrantLock(); + private Thread saveRecordingThread = null; + + private ReentrantLock autoBoneLock = new ReentrantLock(); + private Thread autoBoneThread = null; + + private List listeners = new CopyOnWriteArrayList<>(); + + public AutoBoneHandler(VRServer server) { + this.server = server; + this.poseRecorder = new PoseRecorder(server); + this.autoBone = new AutoBone(server); + } + + public void addListener(AutoBoneListener listener) { + this.listeners.add(listener); + } + + public void removeListener(AutoBoneListener listener) { + this.listeners.removeIf(l -> listener == l); + } + + private void announceProcessStatus( + AutoBoneProcessType processType, + String message, + long current, + long total, + boolean completed, + boolean success + ) { + listeners.forEach(listener -> { + listener + .onAutoBoneProcessStatus(processType, message, current, total, completed, success); + }); + } + + private void announceProcessStatus( + AutoBoneProcessType processType, + String message, + boolean completed, + boolean success + ) { + announceProcessStatus(processType, message, 0, 0, completed, success); + } + + private void announceProcessStatus(AutoBoneProcessType processType, String message) { + announceProcessStatus(processType, message, false, true); + } + + private void announceProcessStatus(AutoBoneProcessType processType, long current, long total) { + announceProcessStatus(processType, null, current, total, false, true); + } + + public String getLengthsString() { + return autoBone.getLengthsString(); + } + + private float processFrames(PoseFrames frames) { + return autoBone + .processFrames(frames, autoBone.calcInitError, autoBone.targetHeight, (epoch) -> { + listeners.forEach(listener -> { + listener.onAutoBoneEpoch(epoch); + }); + }); + } + + public boolean startProcessByType(AutoBoneProcessType processType) { + switch (processType) { + case RECORD: + startRecording(); + break; + + case SAVE: + saveRecording(); + break; + + case PROCESS: + processRecording(); + break; + + case APPLY: + applyValues(); + break; + + default: + return false; + } + + return true; + } + + public void startRecording() { + recordingLock.lock(); + + try { + // Prevent running multiple times + if (recordingThread != null) { + return; + } + + Thread thread = new Thread(this::startRecordingThread); + recordingThread = thread; + thread.start(); + } finally { + recordingLock.unlock(); + } + } + + private void startRecordingThread() { + try { + if (poseRecorder.isReadyToRecord()) { + announceProcessStatus(AutoBoneProcessType.RECORD, "Recording..."); + + // 1000 samples at 20 ms per sample is 20 seconds + int sampleCount = server.config.getInt("autobone.sampleCount", 1000); + long sampleRate = server.config.getLong("autobone.sampleRateMs", 20L); + Future framesFuture = poseRecorder + .startFrameRecording(sampleCount, sampleRate, progress -> { + announceProcessStatus( + AutoBoneProcessType.RECORD, + progress.frame, + progress.totalFrames + ); + }); + PoseFrames frames = framesFuture.get(); + LogManager.info("[AutoBone] Done recording!"); + + if (server.config.getBoolean("autobone.saveRecordings", false)) { + announceProcessStatus(AutoBoneProcessType.RECORD, "Saving recording..."); + autoBone.saveRecording(frames); + } + + listeners.forEach(listener -> { + listener.onAutoBoneRecordingEnd(frames); + }); + + announceProcessStatus(AutoBoneProcessType.RECORD, "Done recording!", true, true); + } else { + announceProcessStatus( + AutoBoneProcessType.RECORD, + "The server is not ready to record", + true, + false + ); + LogManager.severe("[AutoBone] Unable to record..."); + return; + } + } catch (Exception e) { + announceProcessStatus( + AutoBoneProcessType.RECORD, + String.format("Recording failed: %s", e.getMessage()), + true, + false + ); + LogManager.severe("[AutoBone] Failed recording!", e); + } finally { + recordingThread = null; + } + } + + public void saveRecording() { + saveRecordingLock.lock(); + + try { + // Prevent running multiple times + if (saveRecordingThread != null) { + return; + } + + Thread thread = new Thread(this::saveRecordingThread); + saveRecordingThread = thread; + thread.start(); + } finally { + saveRecordingLock.unlock(); + } + } + + private void saveRecordingThread() { + try { + Future framesFuture = poseRecorder.getFramesAsync(); + if (framesFuture != null) { + announceProcessStatus(AutoBoneProcessType.SAVE, "Waiting for recording..."); + PoseFrames frames = framesFuture.get(); + + if (frames.getTrackerCount() <= 0) { + throw new IllegalStateException("Recording has no trackers"); + } + + if (frames.getMaxFrameCount() <= 0) { + throw new IllegalStateException("Recording has no frames"); + } + + announceProcessStatus(AutoBoneProcessType.SAVE, "Saving recording..."); + autoBone.saveRecording(frames); + + announceProcessStatus(AutoBoneProcessType.SAVE, "Recording saved!", true, true); + } else { + announceProcessStatus(AutoBoneProcessType.SAVE, "No recording found", true, false); + LogManager.severe("[AutoBone] Unable to save, no recording was done..."); + return; + } + } catch (Exception e) { + announceProcessStatus( + AutoBoneProcessType.SAVE, + String.format("Failed to save recording: %s", e.getMessage()), + true, + false + ); + LogManager.severe("[AutoBone] Failed to save recording!", e); + } finally { + saveRecordingThread = null; + } + } + + public void processRecording() { + autoBoneLock.lock(); + + try { + // Prevent running multiple times + if (autoBoneThread != null) { + return; + } + + Thread thread = new Thread(this::processRecordingThread); + autoBoneThread = thread; + thread.start(); + } finally { + autoBoneLock.unlock(); + } + } + + private void processRecordingThread() { + try { + announceProcessStatus(AutoBoneProcessType.PROCESS, "Loading recordings..."); + List> frameRecordings = autoBone.loadRecordings(); + + if (!frameRecordings.isEmpty()) { + LogManager.info("[AutoBone] Done loading frames!"); + } else { + Future framesFuture = poseRecorder.getFramesAsync(); + if (framesFuture != null) { + announceProcessStatus(AutoBoneProcessType.PROCESS, "Waiting for recording..."); + PoseFrames frames = framesFuture.get(); + + if (frames.getTrackerCount() <= 0) { + throw new IllegalStateException("Recording has no trackers"); + } + + if (frames.getMaxFrameCount() <= 0) { + throw new IllegalStateException("Recording has no frames"); + } + + frameRecordings.add(Pair.of("", frames)); + } else { + announceProcessStatus( + AutoBoneProcessType.PROCESS, + "No recordings found...", + true, + false + ); + LogManager + .severe( + "[AutoBone] No recordings found in \"" + + AutoBone.getLoadDir().getPath() + + "\" and no recording was done..." + ); + return; + } + } + + announceProcessStatus(AutoBoneProcessType.PROCESS, "Processing recording(s)..."); + LogManager.info("[AutoBone] Processing frames..."); + FastList heightPercentError = new FastList(frameRecordings.size()); + for (Pair recording : frameRecordings) { + LogManager + .info("[AutoBone] Processing frames from \"" + recording.getKey() + "\"..."); + + heightPercentError.add(processFrames(recording.getValue())); + LogManager.info("[AutoBone] Done processing!"); + + // #region Stats/Values + Float neckLength = autoBone.getConfig(SkeletonConfigValue.NECK); + Float chestDistance = autoBone.getConfig(SkeletonConfigValue.CHEST); + Float torsoLength = autoBone.getConfig(SkeletonConfigValue.TORSO); + Float hipWidth = autoBone.getConfig(SkeletonConfigValue.HIPS_WIDTH); + Float legsLength = autoBone.getConfig(SkeletonConfigValue.LEGS_LENGTH); + Float kneeHeight = autoBone.getConfig(SkeletonConfigValue.KNEE_HEIGHT); + + float neckTorso = neckLength != null && torsoLength != null + ? neckLength / torsoLength + : 0f; + float chestTorso = chestDistance != null && torsoLength != null + ? chestDistance / torsoLength + : 0f; + float torsoWaist = hipWidth != null && torsoLength != null + ? hipWidth / torsoLength + : 0f; + float legTorso = legsLength != null && torsoLength != null + ? legsLength / torsoLength + : 0f; + float legBody = legsLength != null && torsoLength != null && neckLength != null + ? legsLength / (torsoLength + neckLength) + : 0f; + float kneeLeg = kneeHeight != null && legsLength != null + ? kneeHeight / legsLength + : 0f; + + LogManager + .info( + "[AutoBone] Ratios: [{Neck-Torso: " + + StringUtils.prettyNumber(neckTorso) + + "}, {Chest-Torso: " + + StringUtils.prettyNumber(chestTorso) + + "}, {Torso-Waist: " + + StringUtils.prettyNumber(torsoWaist) + + "}, {Leg-Torso: " + + StringUtils.prettyNumber(legTorso) + + "}, {Leg-Body: " + + StringUtils.prettyNumber(legBody) + + "}, {Knee-Leg: " + + StringUtils.prettyNumber(kneeLeg) + + "}]" + ); + LogManager.info("[AutoBone] Length values: " + autoBone.getLengthsString()); + } + + if (!heightPercentError.isEmpty()) { + float mean = 0f; + for (float val : heightPercentError) { + mean += val; + } + mean /= heightPercentError.size(); + + float std = 0f; + for (float val : heightPercentError) { + float stdVal = val - mean; + std += stdVal * stdVal; + } + std = (float) Math.sqrt(std / heightPercentError.size()); + + LogManager + .info( + "[AutoBone] Average height error: " + + StringUtils.prettyNumber(mean, 6) + + " (SD " + + StringUtils.prettyNumber(std, 6) + + ")" + ); + } + // #endregion + + listeners.forEach(listener -> { + listener.onAutoBoneEnd(autoBone.configs); + }); + + announceProcessStatus(AutoBoneProcessType.PROCESS, "Done processing!", true, true); + } catch (Exception e) { + announceProcessStatus( + AutoBoneProcessType.PROCESS, + String.format("Processing failed: %s", e.getMessage()), + true, + false + ); + LogManager.severe("[AutoBone] Failed adjustment!", e); + } finally { + autoBoneThread = null; + } + } + + public void applyValues() { + autoBone.applyConfig(); + announceProcessStatus(AutoBoneProcessType.APPLY, "Adjusted values applied!", true, true); + // TODO Update GUI values after applying? Is that needed here? + } +} diff --git a/src/main/java/dev/slimevr/autobone/AutoBoneListener.java b/src/main/java/dev/slimevr/autobone/AutoBoneListener.java new file mode 100644 index 000000000..fa2d19506 --- /dev/null +++ b/src/main/java/dev/slimevr/autobone/AutoBoneListener.java @@ -0,0 +1,26 @@ +package dev.slimevr.autobone; + +import java.util.EnumMap; + +import dev.slimevr.autobone.AutoBone.Epoch; +import dev.slimevr.poserecorder.PoseFrames; +import dev.slimevr.vr.processor.skeleton.SkeletonConfigValue; + + +public interface AutoBoneListener { + + public void onAutoBoneProcessStatus( + AutoBoneProcessType processType, + String message, + long current, + long total, + boolean completed, + boolean success + ); + + public void onAutoBoneRecordingEnd(PoseFrames recording); + + public void onAutoBoneEpoch(Epoch epoch); + + public void onAutoBoneEnd(EnumMap configValues); +} diff --git a/src/main/java/dev/slimevr/autobone/AutoBoneProcessType.java b/src/main/java/dev/slimevr/autobone/AutoBoneProcessType.java new file mode 100644 index 000000000..912f00095 --- /dev/null +++ b/src/main/java/dev/slimevr/autobone/AutoBoneProcessType.java @@ -0,0 +1,31 @@ +package dev.slimevr.autobone; + +import java.util.HashMap; +import java.util.Map; + + +public enum AutoBoneProcessType { + NONE(0), + RECORD(1), + SAVE(2), + PROCESS(3), + APPLY(4); + + public final int id; + + private static final Map byId = new HashMap<>(); + + private AutoBoneProcessType(int id) { + this.id = id; + } + + public static AutoBoneProcessType getById(int id) { + return byId.get(id); + } + + static { + for (AutoBoneProcessType abpt : values()) { + byId.put(abpt.id, abpt); + } + } +} diff --git a/src/main/java/dev/slimevr/gui/AutoBoneWindow.java b/src/main/java/dev/slimevr/gui/AutoBoneWindow.java index 5cab375a7..a22e24fbe 100644 --- a/src/main/java/dev/slimevr/gui/AutoBoneWindow.java +++ b/src/main/java/dev/slimevr/gui/AutoBoneWindow.java @@ -1,38 +1,36 @@ package dev.slimevr.gui; +import javax.swing.BoxLayout; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.JButton; +import javax.swing.border.EmptyBorder; +import java.awt.event.MouseEvent; +import java.util.EnumMap; + +import io.eiren.util.ann.AWTThread; + +import javax.swing.event.MouseInputAdapter; + import dev.slimevr.VRServer; -import dev.slimevr.autobone.AutoBone; +import dev.slimevr.autobone.AutoBoneListener; +import dev.slimevr.autobone.AutoBoneProcessType; +import dev.slimevr.autobone.AutoBone.Epoch; import dev.slimevr.gui.swing.EJBox; import dev.slimevr.poserecorder.PoseFrames; -import dev.slimevr.poserecorder.PoseRecorder; import dev.slimevr.vr.processor.skeleton.SkeletonConfigValue; -import io.eiren.util.StringUtils; -import io.eiren.util.ann.AWTThread; -import io.eiren.util.collections.FastList; -import io.eiren.util.logging.LogManager; -import org.apache.commons.lang3.tuple.Pair; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import javax.swing.event.MouseInputAdapter; -import java.awt.event.MouseEvent; -import java.util.List; -import java.util.concurrent.Future; -public class AutoBoneWindow extends JFrame { +public class AutoBoneWindow extends JFrame implements AutoBoneListener { + + private EJBox pane; private final transient VRServer server; private final transient SkeletonConfigGUI skeletonConfig; - private final transient PoseRecorder poseRecorder; - private final transient AutoBone autoBone; - private final EJBox pane; - private transient Thread recordingThread = null; - private transient Thread saveRecordingThread = null; - private transient Thread autoBoneThread = null; private JButton saveRecordingButton; - private JButton adjustButton; private JButton applyButton; private JLabel processLabel; @@ -43,8 +41,6 @@ public class AutoBoneWindow extends JFrame { this.server = server; this.skeletonConfig = skeletonConfig; - this.poseRecorder = new PoseRecorder(server); - this.autoBone = new AutoBone(server); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); add( @@ -55,16 +51,11 @@ public class AutoBoneWindow extends JFrame { ) ); + server.getAutoBoneHandler().addListener(this); + build(); } - private float processFrames(PoseFrames frames) { - return autoBone - .processFrames(frames, autoBone.calcInitError, autoBone.targetHeight, (epoch) -> { - processLabel.setText(epoch.toString()); - lengthsLabel.setText(autoBone.getLengthsString()); - }); - } @AWTThread private void build() { @@ -76,69 +67,11 @@ public class AutoBoneWindow extends JFrame { addMouseListener(new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent e) { - // Prevent running multiple times - if (!isEnabled() || recordingThread != null) { + if (!isEnabled()) { return; } - Thread thread = new Thread() { - @Override - public void run() { - try { - if (poseRecorder.isReadyToRecord()) { - setText("Recording..."); - // 1000 samples at 20 ms per - // sample is - // 20 seconds - int sampleCount = server.config - .getInt("autobone.sampleCount", 1000); - long sampleRate = server.config - .getLong("autobone.sampleRateMs", 20L); - Future framesFuture = poseRecorder - .startFrameRecording(sampleCount, sampleRate); - PoseFrames frames = framesFuture.get(); - LogManager.info("[AutoBone] Done recording!"); - - saveRecordingButton.setEnabled(true); - adjustButton.setEnabled(true); - - if ( - server.config - .getBoolean( - "autobone.saveRecordings", - false - ) - ) { - setText("Saving..."); - autoBone.saveRecording(frames); - } - } else { - setText("Not Ready..."); - LogManager.severe("[AutoBone] Unable to record..."); - Thread.sleep(3000); // Wait for - // 3 - // seconds - return; - } - } catch (Exception e) { - setText("Recording Failed..."); - LogManager.severe("[AutoBone] Failed recording!", e); - try { - Thread.sleep(3000); // Wait for - // 3 - // seconds - } catch (Exception e1) { - // Ignore - } - } finally { - setText("Start Recording"); - recordingThread = null; - } - } - }; - - recordingThread = thread; - thread.start(); + server.getAutoBoneHandler().startRecording(); } }); } @@ -146,289 +79,30 @@ public class AutoBoneWindow extends JFrame { add(saveRecordingButton = new JButton("Save Recording") { { - setEnabled(poseRecorder.hasRecording()); + setEnabled(false); addMouseListener(new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent e) { - // Prevent running multiple times - if (!isEnabled() || saveRecordingThread != null) { + if (!isEnabled()) { return; } - Thread thread = new Thread() { - @Override - public void run() { - try { - Future framesFuture = poseRecorder - .getFramesAsync(); - if (framesFuture != null) { - setText("Waiting for Recording..."); - PoseFrames frames = framesFuture.get(); - - if (frames.getTrackerCount() <= 0) { - throw new IllegalStateException( - "Recording has no trackers" - ); - } - - if (frames.getMaxFrameCount() <= 0) { - throw new IllegalStateException( - "Recording has no frames" - ); - } - - setText("Saving..."); - autoBone.saveRecording(frames); - - setText("Recording Saved!"); - try { - Thread.sleep(3000); // Wait - // for 3 - // seconds - } catch (Exception e1) { - // Ignore - } - } else { - setText("No Recording..."); - LogManager - .severe( - "[AutoBone] Unable to save, no recording was done..." - ); - try { - Thread.sleep(3000); // Wait - // for 3 - // seconds - } catch (Exception e1) { - // Ignore - } - return; - } - } catch (Exception e) { - setText("Saving Failed..."); - LogManager - .severe("[AutoBone] Failed to save recording!", e); - try { - Thread.sleep(3000); // Wait for - // 3 - // seconds - } catch (Exception e1) { - // Ignore - } - } finally { - setText("Save Recording"); - saveRecordingThread = null; - } - } - }; - - saveRecordingThread = thread; - thread.start(); + server.getAutoBoneHandler().saveRecording(); } }); } }); - add(adjustButton = new JButton("Auto-Adjust") { + add(new JButton("Auto-Adjust") { { - // If there are files to load, enable the button - setEnabled( - poseRecorder.hasRecording() - || (AutoBone.getLoadDir().isDirectory() - && AutoBone.getLoadDir().list().length > 0) - ); addMouseListener(new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent e) { - // Prevent running multiple times - if (!isEnabled() || autoBoneThread != null) { + if (!isEnabled()) { return; } - Thread thread = new Thread() { - @Override - public void run() { - try { - setText("Load..."); - List> frameRecordings = autoBone - .loadRecordings(); - - if (!frameRecordings.isEmpty()) { - LogManager.info("[AutoBone] Done loading frames!"); - } else { - Future framesFuture = poseRecorder - .getFramesAsync(); - if (framesFuture != null) { - setText("Waiting for Recording..."); - PoseFrames frames = framesFuture.get(); - - if (frames.getTrackerCount() <= 0) { - throw new IllegalStateException( - "Recording has no trackers" - ); - } - - if (frames.getMaxFrameCount() <= 0) { - throw new IllegalStateException( - "Recording has no frames" - ); - } - - frameRecordings - .add(Pair.of("", frames)); - } else { - setText("No Recordings..."); - LogManager - .severe( - "[AutoBone] No recordings found in \"" - + AutoBone.getLoadDir().getPath() - + "\" and no recording was done..." - ); - try { - Thread.sleep(3000); // Wait - // for 3 - // seconds - } catch (Exception e1) { - // Ignore - } - return; - } - } - - setText("Processing..."); - LogManager.info("[AutoBone] Processing frames..."); - FastList heightPercentError = new FastList( - frameRecordings.size() - ); - for ( - Pair recording : frameRecordings - ) { - LogManager - .info( - "[AutoBone] Processing frames from \"" - + recording.getKey() - + "\"..." - ); - - heightPercentError - .add(processFrames(recording.getValue())); - LogManager.info("[AutoBone] Done processing!"); - applyButton.setEnabled(true); - - // #region Stats/Values - Float neckLength = autoBone - .getConfig(SkeletonConfigValue.NECK); - Float chestDistance = autoBone - .getConfig(SkeletonConfigValue.CHEST); - Float torsoLength = autoBone - .getConfig(SkeletonConfigValue.TORSO); - Float hipWidth = autoBone - .getConfig(SkeletonConfigValue.HIPS_WIDTH); - Float legsLength = autoBone - .getConfig(SkeletonConfigValue.LEGS_LENGTH); - Float kneeHeight = autoBone - .getConfig(SkeletonConfigValue.KNEE_HEIGHT); - - float neckTorso = neckLength != null - && torsoLength != null - ? neckLength - / torsoLength - : 0f; - float chestTorso = chestDistance != null - && torsoLength != null - ? chestDistance - / torsoLength - : 0f; - float torsoWaist = hipWidth != null - && torsoLength != null - ? hipWidth - / torsoLength - : 0f; - float legTorso = legsLength != null - && torsoLength != null - ? legsLength - / torsoLength - : 0f; - float legBody = legsLength != null - && torsoLength != null - && neckLength != null - ? legsLength - / (torsoLength + neckLength) - : 0f; - float kneeLeg = kneeHeight != null - && legsLength != null - ? kneeHeight - / legsLength - : 0f; - - LogManager - .info( - "[AutoBone] Ratios: [{Neck-Torso: " - + StringUtils.prettyNumber(neckTorso) - + "}, {Chest-Torso: " - + StringUtils.prettyNumber(chestTorso) - + "}, {Torso-Waist: " - + StringUtils.prettyNumber(torsoWaist) - + "}, {Leg-Torso: " - + StringUtils.prettyNumber(legTorso) - + "}, {Leg-Body: " - + StringUtils.prettyNumber(legBody) - + "}, {Knee-Leg: " - + StringUtils.prettyNumber(kneeLeg) - + "}]" - ); - - String lengthsString = autoBone.getLengthsString(); - LogManager - .info( - "[AutoBone] Length values: " + lengthsString - ); - lengthsLabel.setText(lengthsString); - } - - if (!heightPercentError.isEmpty()) { - float mean = 0f; - for (float val : heightPercentError) { - mean += val; - } - mean /= heightPercentError.size(); - - float std = 0f; - for (float val : heightPercentError) { - float stdVal = val - mean; - std += stdVal * stdVal; - } - std = (float) Math - .sqrt(std / heightPercentError.size()); - - LogManager - .info( - "[AutoBone] Average height error: " - + StringUtils.prettyNumber(mean, 6) - + " (SD " - + StringUtils.prettyNumber(std, 6) - + ")" - ); - } - // #endregion - } catch (Exception e) { - setText("Failed..."); - LogManager.severe("[AutoBone] Failed adjustment!", e); - try { - Thread.sleep(3000); // Wait for - // 3 - // seconds - } catch (Exception e1) { - // Ignore - } - } finally { - setText("Auto-Adjust"); - autoBoneThread = null; - } - } - }; - - autoBoneThread = thread; - thread.start(); + server.getAutoBoneHandler().processRecording(); } }); } @@ -444,7 +118,7 @@ public class AutoBoneWindow extends JFrame { return; } - autoBone.applyConfig(); + server.getAutoBoneHandler().applyValues(); // Update GUI values after applying skeletonConfig.refreshAll(); } @@ -464,7 +138,7 @@ public class AutoBoneWindow extends JFrame { pane.add(new EJBox(BoxLayout.LINE_AXIS) { { setBorder(new EmptyBorder(i(5))); - add(lengthsLabel = new JLabel(autoBone.getLengthsString())); + add(lengthsLabel = new JLabel("No config changes")); } }); @@ -473,4 +147,73 @@ public class AutoBoneWindow extends JFrame { setLocationRelativeTo(null); setVisible(false); } + + @Override + public void onAutoBoneProcessStatus( + AutoBoneProcessType processType, + String message, + long current, + long total, + boolean completed, + boolean success + ) { + if (message != null) { + if (total == 0) { + processLabel.setText(String.format("%s: %s", processType.name(), message)); + } else { + processLabel + .setText( + String + .format( + "%s (%d/%d) [%.2f%%]: %s", + processType.name(), + current, + total, + (current / (double) total) * 100.0, + message + ) + ); + } + } else { + if (total != 0) { + processLabel + .setText( + String + .format( + "%s (%d/%d) [%.2f%%]", + processType.name(), + current, + total, + (current / (double) total) * 100.0 + ) + ); + } + } + } + + @Override + public void onAutoBoneRecordingEnd(PoseFrames recording) { + saveRecordingButton.setEnabled(true); + } + + @Override + public void onAutoBoneEpoch(Epoch epoch) { + processLabel + .setText( + String + .format( + "PROCESS: Epoch %d/%d (%.2f%%) Error: %.4f", + epoch.epoch, + epoch.totalEpochs, + (epoch.epoch / (double) epoch.totalEpochs) * 100.0, + epoch.epochError + ) + ); + lengthsLabel.setText(server.getAutoBoneHandler().getLengthsString()); + } + + @Override + public void onAutoBoneEnd(EnumMap configValues) { + applyButton.setEnabled(true); + } } diff --git a/src/main/java/dev/slimevr/poserecorder/PoseRecorder.java b/src/main/java/dev/slimevr/poserecorder/PoseRecorder.java index bcc539d35..2886878a1 100644 --- a/src/main/java/dev/slimevr/poserecorder/PoseRecorder.java +++ b/src/main/java/dev/slimevr/poserecorder/PoseRecorder.java @@ -1,27 +1,44 @@ package dev.slimevr.poserecorder; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.function.Consumer; + +import org.apache.commons.lang3.tuple.Pair; + import dev.slimevr.VRServer; import dev.slimevr.util.ann.VRServerThread; import dev.slimevr.vr.trackers.Tracker; import io.eiren.util.collections.FastList; import io.eiren.util.logging.LogManager; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; public class PoseRecorder { - protected final VRServer server; + public class RecordingProgress { + + public final int frame; + public final int totalFrames; + + public RecordingProgress(int frame, int totalFrames) { + this.frame = frame; + this.totalFrames = totalFrames; + } + } + protected PoseFrames poseFrame = null; + protected int numFrames = -1; protected int frameCursor = 0; protected long frameRecordingInterval = 60L; protected long nextFrameTimeMs = -1L; + protected CompletableFuture currentRecording; + protected Consumer currentFrameCallback; + + protected final VRServer server; FastList> trackers = new FastList>(); public PoseRecorder(VRServer server) { @@ -72,6 +89,10 @@ public class PoseRecorder { tracker.getRight().addFrame(cursor, tracker.getLeft()); } + if (currentFrameCallback != null) { + currentFrameCallback.accept(new RecordingProgress(frameCursor, numFrames)); + } + // If done, send finished recording if (frameCursor >= numFrames) { stopFrameRecording(); @@ -80,13 +101,30 @@ public class PoseRecorder { } public synchronized Future startFrameRecording(int numFrames, long intervalMs) { - return startFrameRecording(numFrames, intervalMs, server.getAllTrackers()); + return startFrameRecording(numFrames, intervalMs, server.getAllTrackers(), null); + } + + public synchronized Future startFrameRecording( + int numFrames, + long intervalMs, + Consumer frameCallback + ) { + return startFrameRecording(numFrames, intervalMs, server.getAllTrackers(), frameCallback); } public synchronized Future startFrameRecording( int numFrames, long intervalMs, List trackers + ) { + return startFrameRecording(numFrames, intervalMs, trackers, null); + } + + public synchronized Future startFrameRecording( + int numFrames, + long intervalMs, + List trackers, + Consumer frameCallback ) { if (numFrames < 1) { throw new IllegalArgumentException("numFrames must at least have a value of 1"); @@ -139,6 +177,7 @@ public class PoseRecorder { + " ms frame interval" ); + currentFrameCallback = frameCallback; currentRecording = new CompletableFuture(); return currentRecording; } diff --git a/src/main/java/dev/slimevr/protocol/ConnectionContext.java b/src/main/java/dev/slimevr/protocol/ConnectionContext.java index 5c89601ff..93c0152f9 100644 --- a/src/main/java/dev/slimevr/protocol/ConnectionContext.java +++ b/src/main/java/dev/slimevr/protocol/ConnectionContext.java @@ -17,6 +17,7 @@ public class ConnectionContext { private final List dataFeedTimers = new ArrayList<>(); private boolean useSerial = false; + private boolean useAutoBone = false; public List getDataFeedConfigList() { return dataFeedConfigList; @@ -33,4 +34,12 @@ public class ConnectionContext { public void setUseSerial(boolean useSerial) { this.useSerial = useSerial; } + + public boolean useAutoBone() { + return useAutoBone; + } + + public void setUseAutoBone(boolean useAutoBone) { + this.useAutoBone = useAutoBone; + } } diff --git a/src/main/java/dev/slimevr/protocol/RPCHandler.java b/src/main/java/dev/slimevr/protocol/RPCHandler.java index 9253860e9..af4d43c36 100644 --- a/src/main/java/dev/slimevr/protocol/RPCHandler.java +++ b/src/main/java/dev/slimevr/protocol/RPCHandler.java @@ -3,7 +3,12 @@ package dev.slimevr.protocol; import com.fazecast.jSerialComm.SerialPort; import com.google.flatbuffers.FlatBufferBuilder; import com.jme3.math.Quaternion; + +import dev.slimevr.autobone.AutoBoneListener; +import dev.slimevr.autobone.AutoBoneProcessType; +import dev.slimevr.autobone.AutoBone.Epoch; import dev.slimevr.platform.windows.WindowsNamedPipeBridge; +import dev.slimevr.poserecorder.PoseFrames; import dev.slimevr.serial.SerialListener; import dev.slimevr.vr.processor.skeleton.SkeletonConfigValue; import dev.slimevr.vr.trackers.*; @@ -12,10 +17,13 @@ import solarxr_protocol.MessageBundle; import solarxr_protocol.datatypes.TransactionId; import solarxr_protocol.rpc.*; +import java.util.EnumMap; +import java.util.Map.Entry; import java.util.function.BiConsumer; -public class RPCHandler extends ProtocolHandler implements SerialListener { +public class RPCHandler extends ProtocolHandler + implements SerialListener, AutoBoneListener { private final ProtocolAPI api; @@ -43,7 +51,10 @@ public class RPCHandler extends ProtocolHandler implements Ser registerPacketListener(RpcMessage.OpenSerialRequest, this::onOpenSerialRequest); registerPacketListener(RpcMessage.CloseSerialRequest, this::onCloseSerialRequest); + registerPacketListener(RpcMessage.AutoBoneProcessRequest, this::onAutoBoneProcessRequest); + this.api.server.getSerialHandler().addListener(this); + this.api.server.getAutoBoneHandler().addListener(this); } public void onSetWifiRequest(GenericConnection conn, RpcMessageHeader messageHeader) { @@ -366,4 +377,113 @@ public class RPCHandler extends ProtocolHandler implements Ser }); }); } + + public void onAutoBoneProcessRequest(GenericConnection conn, RpcMessageHeader messageHeader) { + AutoBoneProcessRequest req = (AutoBoneProcessRequest) messageHeader + .message(new AutoBoneProcessRequest()); + if (req == null || conn.getContext().useAutoBone()) + return; + + conn.getContext().setUseAutoBone(true); + this.api.server + .getAutoBoneHandler() + .startProcessByType(AutoBoneProcessType.getById(req.processType())); + } + + @Override + public void onAutoBoneProcessStatus( + AutoBoneProcessType processType, + String message, + long current, + long total, + boolean completed, + boolean success + ) { + this.api.getAPIServers().forEach((server) -> { + server + .getAPIConnections() + .filter(conn -> conn.getContext().useAutoBone()) + .forEach((conn) -> { + FlatBufferBuilder fbb = new FlatBufferBuilder(32); + + Integer messageOffset = message != null ? fbb.createString(message) : null; + + AutoBoneProcessStatusResponse.startAutoBoneProcessStatusResponse(fbb); + AutoBoneProcessStatusResponse.addProcessType(fbb, processType.id); + if (messageOffset != null) + AutoBoneProcessStatusResponse.addMessage(fbb, messageOffset); + if (total > 0 && current >= 0) { + AutoBoneProcessStatusResponse.addCurrent(fbb, current); + AutoBoneProcessStatusResponse.addTotal(fbb, total); + } + AutoBoneProcessStatusResponse.addCompleted(fbb, completed); + AutoBoneProcessStatusResponse.addSuccess(fbb, success); + int update = AutoBoneProcessStatusResponse + .endAutoBoneProcessStatusResponse(fbb); + int outbound = this + .createRPCMessage(fbb, RpcMessage.AutoBoneProcessStatusResponse, update); + fbb.finish(outbound); + + conn.send(fbb.dataBuffer()); + if (completed) { + conn.getContext().setUseAutoBone(false); + } + }); + }); + } + + @Override + public void onAutoBoneRecordingEnd(PoseFrames recording) { + // Do nothing, this is broadcasted by "onAutoBoneProcessStatus" uwu + } + + @Override + public void onAutoBoneEpoch(Epoch epoch) { + this.api.getAPIServers().forEach((server) -> { + server + .getAPIConnections() + .filter(conn -> conn.getContext().useAutoBone()) + .forEach((conn) -> { + FlatBufferBuilder fbb = new FlatBufferBuilder(32); + + int[] skeletonPartOffsets = new int[epoch.configValues.size()]; + int i = 0; + for ( + Entry skeletonConfig : epoch.configValues + .entrySet() + ) { + skeletonPartOffsets[i++] = SkeletonPart + .createSkeletonPart( + fbb, + skeletonConfig.getKey().id, + skeletonConfig.getValue() + ); + } + + int skeletonPartsOffset = AutoBoneEpochResponse + .createAdjustedSkeletonPartsVector(fbb, skeletonPartOffsets); + + int update = AutoBoneEpochResponse + .createAutoBoneEpochResponse( + fbb, + epoch.epoch, + epoch.totalEpochs, + epoch.epochError, + skeletonPartsOffset + ); + int outbound = this + .createRPCMessage(fbb, RpcMessage.AutoBoneEpochResponse, update); + fbb.finish(outbound); + + conn.send(fbb.dataBuffer()); + }); + }); + } + + + @Override + public void onAutoBoneEnd(EnumMap configValues) { + // Do nothing, the last epoch from "onAutoBoneEpoch" should be all + // that's needed + } } diff --git a/src/main/java/dev/slimevr/serial/SerialHandler.java b/src/main/java/dev/slimevr/serial/SerialHandler.java index 835677af4..2c2e5623a 100644 --- a/src/main/java/dev/slimevr/serial/SerialHandler.java +++ b/src/main/java/dev/slimevr/serial/SerialHandler.java @@ -9,13 +9,13 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.List; public class SerialHandler implements SerialPortMessageListener { - private final List listeners = new ArrayList<>(); + private final List listeners = new CopyOnWriteArrayList<>(); private SerialPort trackerPort = null; public void addListener(SerialListener channel) {