mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-24 02:51:20 -08:00
Merge remote-tracking branch 'gui/main' into merge-gui-and-server
This commit is contained in:
commit
ae94de39b1
430 files changed
+44297
-50
No files matched your search
@@ -0,0 +1,117 @@
|
||||
package dev.slimevr;
|
||||
|
||||
import dev.slimevr.gui.Keybinding;
|
||||
import dev.slimevr.gui.VRServerGUI;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import org.apache.commons.cli.*;
|
||||
import org.apache.commons.lang3.JavaVersion;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
|
||||
|
||||
public class Main {
|
||||
|
||||
public static String VERSION = "0.2.1";
|
||||
|
||||
public static VRServer vrServer;
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("awt.useSystemAAFontSettings", "on");
|
||||
System.setProperty("swing.aatext", "true");
|
||||
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
CommandLine cmd = null;
|
||||
|
||||
Options options = new Options();
|
||||
|
||||
Option noGui = new Option(
|
||||
"g",
|
||||
"no-gui",
|
||||
false,
|
||||
"disable swing gui (allow for other gui to be used)"
|
||||
);
|
||||
Option help = new Option("h", "help", false, "Show help");
|
||||
|
||||
options.addOption(noGui);
|
||||
options.addOption(help);
|
||||
try {
|
||||
cmd = parser.parse(options, args);
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp("slimevr.jar", options);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
if (cmd.hasOption("help")) {
|
||||
formatter.printHelp("slimevr.jar", options);
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
File dir = new File("").getAbsoluteFile();
|
||||
try {
|
||||
LogManager.initialize(new File(dir, "logs/"), dir);
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
if (!SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_17)) {
|
||||
LogManager.severe("SlimeVR start-up error! A minimum of Java 17 is required.");
|
||||
JOptionPane
|
||||
.showMessageDialog(
|
||||
null,
|
||||
"SlimeVR start-up error! A minimum of Java 17 is required.",
|
||||
"SlimeVR: Java Runtime Mismatch",
|
||||
JOptionPane.ERROR_MESSAGE
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
new ServerSocket(6969).close();
|
||||
new ServerSocket(35903).close();
|
||||
new ServerSocket(21110).close();
|
||||
} catch (IOException e) {
|
||||
LogManager
|
||||
.severe(
|
||||
"SlimeVR start-up error! Required ports are busy. Make sure there is no other instance of SlimeVR Server running."
|
||||
);
|
||||
JOptionPane
|
||||
.showMessageDialog(
|
||||
null,
|
||||
"SlimeVR start-up error! Required ports are busy. Make sure there is no other instance of SlimeVR Server running.",
|
||||
"SlimeVR: Ports are busy",
|
||||
JOptionPane.ERROR_MESSAGE
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
vrServer = new VRServer();
|
||||
vrServer.start();
|
||||
new Keybinding(vrServer);
|
||||
if (!cmd.hasOption("no-gui"))
|
||||
new VRServerGUI(vrServer);
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
try {
|
||||
Thread.sleep(2000L);
|
||||
} catch (InterruptedException e2) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.exit(1); // Exit in case error happened on init and window
|
||||
// not appeared, but some thread
|
||||
// started
|
||||
} finally {
|
||||
try {
|
||||
Thread.sleep(2000L);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.slimevr;
|
||||
|
||||
public enum NetworkProtocol {
|
||||
OWO_LEGACY,
|
||||
SLIMEVR_RAW,
|
||||
SLIMEVR_FLATBUFFER,
|
||||
SLIMEVR_WEBSOCKET
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package dev.slimevr;
|
||||
|
||||
import com.jme3.system.NanoTimer;
|
||||
import dev.slimevr.autobone.AutoBoneHandler;
|
||||
import dev.slimevr.bridge.Bridge;
|
||||
import dev.slimevr.bridge.VMCBridge;
|
||||
import dev.slimevr.config.ConfigManager;
|
||||
import dev.slimevr.platform.windows.WindowsNamedPipeBridge;
|
||||
import dev.slimevr.poserecorder.BVHRecorder;
|
||||
import dev.slimevr.protocol.ProtocolAPI;
|
||||
import dev.slimevr.serial.SerialHandler;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.DeviceManager;
|
||||
import dev.slimevr.vr.processor.HumanPoseProcessor;
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
import dev.slimevr.vr.trackers.HMDTracker;
|
||||
import dev.slimevr.vr.trackers.ShareableTracker;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import dev.slimevr.vr.trackers.udp.TrackersUDPServer;
|
||||
import dev.slimevr.websocketapi.WebSocketVRBridge;
|
||||
import io.eiren.util.OperatingSystem;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
import io.eiren.util.ann.ThreadSecure;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import solarxr_protocol.datatypes.TrackerIdT;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
|
||||
public class VRServer extends Thread {
|
||||
|
||||
public final HumanPoseProcessor humanPoseProcessor;
|
||||
public final HMDTracker hmdTracker;
|
||||
private final List<Tracker> trackers = new FastList<>();
|
||||
private final TrackersUDPServer trackersServer;
|
||||
private final List<Bridge> bridges = new FastList<>();
|
||||
private final Queue<Runnable> tasks = new LinkedBlockingQueue<>();
|
||||
private final List<Consumer<Tracker>> newTrackersConsumers = new FastList<>();
|
||||
private final List<Runnable> onTick = new FastList<>();
|
||||
private final List<? extends ShareableTracker> shareTrackers;
|
||||
private final DeviceManager deviceManager;
|
||||
private final BVHRecorder bvhRecorder;
|
||||
private final SerialHandler serialHandler;
|
||||
private final AutoBoneHandler autoBoneHandler;
|
||||
private final ProtocolAPI protocolAPI;
|
||||
private final ConfigManager configManager;
|
||||
private final NanoTimer fpsTimer = new NanoTimer();
|
||||
|
||||
/**
|
||||
* This function is used by VRWorkout, do not remove!
|
||||
*/
|
||||
public VRServer() {
|
||||
this("vrconfig.yml");
|
||||
}
|
||||
|
||||
public VRServer(String configPath) {
|
||||
super("VRServer");
|
||||
|
||||
this.configManager = new ConfigManager(configPath);
|
||||
this.configManager.loadConfig();
|
||||
|
||||
deviceManager = new DeviceManager(this);
|
||||
|
||||
serialHandler = new SerialHandler();
|
||||
autoBoneHandler = new AutoBoneHandler(this);
|
||||
protocolAPI = new ProtocolAPI(this);
|
||||
|
||||
hmdTracker = new HMDTracker("HMD");
|
||||
hmdTracker.position.set(0, 1.8f, 0); // Set starting position for easier
|
||||
// debugging
|
||||
// TODO Multiple processors
|
||||
humanPoseProcessor = new HumanPoseProcessor(this, hmdTracker);
|
||||
shareTrackers = humanPoseProcessor.getComputedTrackers();
|
||||
|
||||
// Start server for SlimeVR trackers
|
||||
trackersServer = new TrackersUDPServer(6969, "Sensors UDP server", this::registerTracker);
|
||||
|
||||
// OpenVR bridge currently only supports Windows
|
||||
if (OperatingSystem.getCurrentPlatform() == OperatingSystem.WINDOWS) {
|
||||
|
||||
// Create named pipe bridge for SteamVR driver
|
||||
WindowsNamedPipeBridge driverBridge = new WindowsNamedPipeBridge(
|
||||
this,
|
||||
hmdTracker,
|
||||
"steamvr",
|
||||
"SteamVR Driver Bridge",
|
||||
"\\\\.\\pipe\\SlimeVRDriver",
|
||||
shareTrackers
|
||||
);
|
||||
tasks.add(driverBridge::startBridge);
|
||||
bridges.add(driverBridge);
|
||||
|
||||
// Create named pipe bridge for SteamVR input
|
||||
// TODO: how do we want to handle HMD input from the feeder app?
|
||||
WindowsNamedPipeBridge feederBridge = new WindowsNamedPipeBridge(
|
||||
this,
|
||||
null,
|
||||
"steamvr_feeder",
|
||||
"SteamVR Feeder Bridge",
|
||||
"\\\\.\\pipe\\SlimeVRInput",
|
||||
new FastList<>()
|
||||
);
|
||||
tasks.add(feederBridge::startBridge);
|
||||
bridges.add(feederBridge);
|
||||
}
|
||||
|
||||
// Create WebSocket server
|
||||
WebSocketVRBridge wsBridge = new WebSocketVRBridge(hmdTracker, shareTrackers, this);
|
||||
tasks.add(wsBridge::startBridge);
|
||||
bridges.add(wsBridge);
|
||||
|
||||
// Create VMCBridge
|
||||
try {
|
||||
VMCBridge vmcBridge = new VMCBridge(39539, 39540, InetAddress.getLocalHost());
|
||||
tasks.add(vmcBridge::startBridge);
|
||||
bridges.add(vmcBridge);
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
bvhRecorder = new BVHRecorder(this);
|
||||
|
||||
registerTracker(hmdTracker);
|
||||
for (Tracker tracker : shareTrackers) {
|
||||
registerTracker(tracker);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasBridge(Class<? extends Bridge> bridgeClass) {
|
||||
for (Bridge bridge : bridges) {
|
||||
if (bridgeClass.isAssignableFrom(bridge.getClass())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public <E extends Bridge> E getVRBridge(Class<E> bridgeClass) {
|
||||
for (Bridge bridge : bridges) {
|
||||
if (bridgeClass.isAssignableFrom(bridge.getClass())) {
|
||||
return bridgeClass.cast(bridge);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public void addOnTick(Runnable runnable) {
|
||||
this.onTick.add(runnable);
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void addNewTrackerConsumer(Consumer<Tracker> consumer) {
|
||||
queueTask(() -> {
|
||||
newTrackersConsumers.add(consumer);
|
||||
for (Tracker tracker : trackers) {
|
||||
consumer.accept(tracker);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void trackerUpdated(Tracker tracker) {
|
||||
queueTask(() -> {
|
||||
humanPoseProcessor.trackerUpdated(tracker);
|
||||
this.getConfigManager().getVrConfig().writeTrackerConfig(tracker);
|
||||
this.getConfigManager().saveConfig();
|
||||
});
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void addSkeletonUpdatedCallback(Consumer<Skeleton> consumer) {
|
||||
queueTask(() -> humanPoseProcessor.addSkeletonUpdatedCallback(consumer));
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void run() {
|
||||
trackersServer.start();
|
||||
while (true) {
|
||||
fpsTimer.update();
|
||||
// final long start = System.currentTimeMillis();
|
||||
do {
|
||||
Runnable task = tasks.poll();
|
||||
if (task == null)
|
||||
break;
|
||||
task.run();
|
||||
} while (true);
|
||||
for (Runnable task : onTick) {
|
||||
task.run();
|
||||
}
|
||||
for (Bridge bridge : bridges) {
|
||||
bridge.dataRead();
|
||||
}
|
||||
for (Tracker tracker : trackers) {
|
||||
tracker.tick();
|
||||
}
|
||||
humanPoseProcessor.update();
|
||||
for (Bridge bridge : bridges) {
|
||||
bridge.dataWrite();
|
||||
}
|
||||
// final long time = System.currentTimeMillis() - start;
|
||||
try {
|
||||
Thread.sleep(1); // 1000Hz
|
||||
} catch (InterruptedException ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void queueTask(Runnable r) {
|
||||
tasks.add(r);
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
private void trackerAdded(Tracker tracker) {
|
||||
humanPoseProcessor.trackerAdded(tracker);
|
||||
}
|
||||
|
||||
@ThreadSecure
|
||||
public void registerTracker(Tracker tracker) {
|
||||
this.getConfigManager().getVrConfig().readTrackerConfig(tracker);
|
||||
queueTask(() -> {
|
||||
trackers.add(tracker);
|
||||
trackerAdded(tracker);
|
||||
for (Consumer<Tracker> tc : newTrackersConsumers) {
|
||||
tc.accept(tracker);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void resetTrackers() {
|
||||
queueTask(humanPoseProcessor::resetTrackers);
|
||||
}
|
||||
|
||||
public void resetTrackersYaw() {
|
||||
queueTask(humanPoseProcessor::resetTrackersYaw);
|
||||
}
|
||||
|
||||
public void setLegTweaksEnabled(boolean value) {
|
||||
queueTask(() -> humanPoseProcessor.setLegTweaksEnabled(value));
|
||||
}
|
||||
|
||||
public void setSkatingReductionEnabled(boolean value) {
|
||||
queueTask(() -> humanPoseProcessor.setSkatingCorrectionEnabled(value));
|
||||
}
|
||||
|
||||
public void setFloorClipEnabled(boolean value) {
|
||||
queueTask(() -> humanPoseProcessor.setFloorClipEnabled(value));
|
||||
}
|
||||
|
||||
public int getTrackersCount() {
|
||||
return trackers.size();
|
||||
}
|
||||
|
||||
public List<Tracker> getAllTrackers() {
|
||||
return new FastList<>(trackers);
|
||||
}
|
||||
|
||||
public Tracker getTrackerById(TrackerIdT id) {
|
||||
for (Tracker tracker : trackers) {
|
||||
if (tracker.getTrackerNum() != id.getTrackerNum()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle synthetic devices
|
||||
if (id.getDeviceId() == null && tracker.getDevice() == null) {
|
||||
return tracker;
|
||||
}
|
||||
|
||||
if (
|
||||
tracker.getDevice() != null
|
||||
&& id.getDeviceId() != null
|
||||
&& id.getDeviceId().getId() == tracker.getDevice().getId()
|
||||
) {
|
||||
// This is a physical tracker, and both device id and the
|
||||
// tracker num match
|
||||
return tracker;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public BVHRecorder getBvhRecorder() {
|
||||
return this.bvhRecorder;
|
||||
}
|
||||
|
||||
public SerialHandler getSerialHandler() {
|
||||
return this.serialHandler;
|
||||
}
|
||||
|
||||
public AutoBoneHandler getAutoBoneHandler() {
|
||||
return this.autoBoneHandler;
|
||||
}
|
||||
|
||||
public ProtocolAPI getProtocolAPI() {
|
||||
return protocolAPI;
|
||||
}
|
||||
|
||||
public TrackersUDPServer getTrackersServer() {
|
||||
return trackersServer;
|
||||
}
|
||||
|
||||
public DeviceManager getDeviceManager() {
|
||||
return deviceManager;
|
||||
}
|
||||
|
||||
public ConfigManager getConfigManager() {
|
||||
return configManager;
|
||||
}
|
||||
|
||||
public NanoTimer getFpsTimer() {
|
||||
return fpsTimer;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
package dev.slimevr.autobone;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.autobone.errors.*;
|
||||
import dev.slimevr.config.AutoBoneConfig;
|
||||
import dev.slimevr.poserecorder.PoseFrameIO;
|
||||
import dev.slimevr.poserecorder.PoseFrameSkeleton;
|
||||
import dev.slimevr.poserecorder.PoseFrameTracker;
|
||||
import dev.slimevr.poserecorder.PoseFrames;
|
||||
import dev.slimevr.vr.processor.HumanPoseProcessor;
|
||||
import dev.slimevr.vr.processor.TransformNode;
|
||||
import dev.slimevr.vr.processor.skeleton.*;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Random;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
|
||||
public class AutoBone {
|
||||
|
||||
private static final File saveDir = new File("AutoBone Recordings");
|
||||
private static final File loadDir = new File("Load AutoBone Recordings");
|
||||
|
||||
// This is filled by reloadConfigValues()
|
||||
public final EnumMap<BoneType, Float> offsets = new EnumMap<>(
|
||||
BoneType.class
|
||||
);
|
||||
|
||||
public final FastList<BoneType> adjustOffsets = new FastList<>(
|
||||
new BoneType[] {
|
||||
BoneType.HEAD,
|
||||
BoneType.NECK,
|
||||
BoneType.CHEST,
|
||||
BoneType.WAIST,
|
||||
BoneType.HIP,
|
||||
|
||||
// This now works when using body proportion error! It's not the
|
||||
// best still but it is somewhat functional
|
||||
BoneType.LEFT_HIP,
|
||||
|
||||
BoneType.LEFT_UPPER_LEG,
|
||||
BoneType.LEFT_LOWER_LEG,
|
||||
}
|
||||
);
|
||||
|
||||
public final FastList<BoneType> heightOffsets = new FastList<>(
|
||||
new BoneType[] {
|
||||
BoneType.NECK,
|
||||
BoneType.CHEST,
|
||||
BoneType.WAIST,
|
||||
BoneType.HIP,
|
||||
|
||||
BoneType.LEFT_UPPER_LEG,
|
||||
BoneType.RIGHT_UPPER_LEG,
|
||||
BoneType.LEFT_LOWER_LEG,
|
||||
BoneType.RIGHT_LOWER_LEG,
|
||||
}
|
||||
);
|
||||
|
||||
public final FastList<SkeletonConfigOffsets> legacyHeightConfigs = new FastList<>(
|
||||
new SkeletonConfigOffsets[] {
|
||||
SkeletonConfigOffsets.NECK,
|
||||
SkeletonConfigOffsets.TORSO,
|
||||
|
||||
SkeletonConfigOffsets.LEGS_LENGTH,
|
||||
}
|
||||
);
|
||||
|
||||
public final EnumMap<SkeletonConfigOffsets, Float> legacyConfigs = new EnumMap<>(
|
||||
SkeletonConfigOffsets.class
|
||||
);
|
||||
|
||||
protected final VRServer server;
|
||||
|
||||
// #region Error functions
|
||||
public SlideError slideError = new SlideError();
|
||||
public OffsetSlideError offsetSlideError = new OffsetSlideError();
|
||||
public FootHeightOffsetError footHeightOffsetError = new FootHeightOffsetError();
|
||||
public BodyProportionError bodyProportionError = new BodyProportionError();
|
||||
public HeightError heightError = new HeightError();
|
||||
public PositionError positionError = new PositionError();
|
||||
public PositionOffsetError positionOffsetError = new PositionOffsetError();
|
||||
// #endregion
|
||||
|
||||
private final Random rand = new Random();
|
||||
|
||||
private final AutoBoneConfig config;
|
||||
|
||||
public AutoBone(VRServer server) {
|
||||
this.config = server.getConfigManager().getVrConfig().getAutoBone();
|
||||
this.server = server;
|
||||
reloadConfigValues();
|
||||
}
|
||||
|
||||
// Mean square error function
|
||||
protected static float errorFunc(float errorDeriv) {
|
||||
return 0.5f * (errorDeriv * errorDeriv);
|
||||
}
|
||||
|
||||
public static File getLoadDir() {
|
||||
return loadDir;
|
||||
}
|
||||
|
||||
public float computeBoneOffset(BoneType bone, SkeletonConfig skeletonConfig) {
|
||||
return switch (bone) {
|
||||
case HEAD -> skeletonConfig.getOffset(SkeletonConfigOffsets.HEAD);
|
||||
case NECK -> skeletonConfig.getOffset(SkeletonConfigOffsets.NECK);
|
||||
case CHEST -> skeletonConfig.getOffset(SkeletonConfigOffsets.CHEST);
|
||||
case WAIST -> -skeletonConfig.getOffset(SkeletonConfigOffsets.CHEST)
|
||||
+ skeletonConfig.getOffset(SkeletonConfigOffsets.TORSO)
|
||||
- skeletonConfig.getOffset(SkeletonConfigOffsets.WAIST);
|
||||
case HIP -> skeletonConfig.getOffset(SkeletonConfigOffsets.WAIST);
|
||||
case LEFT_HIP, RIGHT_HIP -> skeletonConfig.getOffset(SkeletonConfigOffsets.HIPS_WIDTH)
|
||||
/ 2f;
|
||||
case LEFT_UPPER_LEG, RIGHT_UPPER_LEG -> skeletonConfig
|
||||
.getOffset(SkeletonConfigOffsets.LEGS_LENGTH)
|
||||
- skeletonConfig.getOffset(SkeletonConfigOffsets.KNEE_HEIGHT);
|
||||
case LEFT_LOWER_LEG, RIGHT_LOWER_LEG -> skeletonConfig
|
||||
.getOffset(SkeletonConfigOffsets.KNEE_HEIGHT);
|
||||
default -> -1f;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public void reloadConfigValues() {
|
||||
reloadConfigValues(null);
|
||||
}
|
||||
|
||||
public void reloadConfigValues(List<PoseFrameTracker> trackers) {
|
||||
// Remove all previous values
|
||||
offsets.clear();
|
||||
|
||||
// Get current or default skeleton configs
|
||||
Skeleton skeleton = getSkeleton();
|
||||
SkeletonConfig skeletonConfig = skeleton != null
|
||||
? skeleton.getSkeletonConfig()
|
||||
: new SkeletonConfig(false);
|
||||
|
||||
for (BoneType bone : adjustOffsets) {
|
||||
float offset = computeBoneOffset(bone, skeletonConfig);
|
||||
if (offset > 0f) {
|
||||
offsets.put(bone, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Vector3f getBoneDirection(
|
||||
HumanSkeleton skeleton,
|
||||
BoneType node,
|
||||
boolean rightSide,
|
||||
Vector3f buffer
|
||||
) {
|
||||
if (buffer == null) {
|
||||
buffer = new Vector3f();
|
||||
}
|
||||
|
||||
switch (node) {
|
||||
case LEFT_HIP, RIGHT_HIP -> node = rightSide ? BoneType.RIGHT_HIP : BoneType.LEFT_HIP;
|
||||
case LEFT_UPPER_LEG, RIGHT_UPPER_LEG -> node = rightSide
|
||||
? BoneType.RIGHT_UPPER_LEG
|
||||
: BoneType.LEFT_UPPER_LEG;
|
||||
case LEFT_LOWER_LEG, RIGHT_LOWER_LEG -> node = rightSide
|
||||
? BoneType.RIGHT_LOWER_LEG
|
||||
: BoneType.LEFT_LOWER_LEG;
|
||||
}
|
||||
|
||||
TransformNode relevantTransform = skeleton.getTailNodeOfBone(node);
|
||||
return relevantTransform.worldTransform
|
||||
.getTranslation()
|
||||
.subtract(relevantTransform.getParent().worldTransform.getTranslation(), buffer)
|
||||
.normalizeLocal();
|
||||
}
|
||||
|
||||
public float getDotProductDiff(
|
||||
HumanSkeleton skeleton1,
|
||||
HumanSkeleton skeleton2,
|
||||
BoneType node,
|
||||
boolean rightSide,
|
||||
Vector3f offset
|
||||
) {
|
||||
Vector3f normalizedOffset = offset.normalize();
|
||||
|
||||
Vector3f boneRotation = new Vector3f();
|
||||
getBoneDirection(skeleton1, node, rightSide, boneRotation);
|
||||
float dot1 = normalizedOffset.dot(boneRotation);
|
||||
|
||||
getBoneDirection(skeleton2, node, rightSide, boneRotation);
|
||||
float dot2 = normalizedOffset.dot(boneRotation);
|
||||
|
||||
return dot2 - dot1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple utility method to get the {@link Skeleton} from the
|
||||
* {@link VRServer}
|
||||
*
|
||||
* @return The {@link Skeleton} associated with the {@link VRServer}, or
|
||||
* null if there is none available
|
||||
* @see {@link VRServer}, {@link Skeleton}
|
||||
*/
|
||||
private Skeleton getSkeleton() {
|
||||
HumanPoseProcessor humanPoseProcessor = server != null ? server.humanPoseProcessor : null;
|
||||
return humanPoseProcessor != null ? humanPoseProcessor.getSkeleton() : null;
|
||||
}
|
||||
|
||||
public void applyAndSaveConfig() {
|
||||
if (!applyAndSaveConfig(getSkeleton())) {
|
||||
// Unable to apply to skeleton, save directly
|
||||
// saveConfigs();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean applyConfig(
|
||||
BiConsumer<SkeletonConfigOffsets, Float> configConsumer,
|
||||
Map<BoneType, Float> offsets
|
||||
) {
|
||||
if (configConsumer == null || offsets == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Float headOffset = offsets.get(BoneType.HEAD);
|
||||
if (headOffset != null) {
|
||||
configConsumer.accept(SkeletonConfigOffsets.HEAD, headOffset);
|
||||
}
|
||||
|
||||
Float neckOffset = offsets.get(BoneType.NECK);
|
||||
if (neckOffset != null) {
|
||||
configConsumer.accept(SkeletonConfigOffsets.NECK, neckOffset);
|
||||
}
|
||||
|
||||
Float chestOffset = offsets.get(BoneType.CHEST);
|
||||
Float hipOffset = offsets.get(BoneType.HIP);
|
||||
Float waistOffset = offsets.get(BoneType.WAIST);
|
||||
if (chestOffset != null && hipOffset != null && waistOffset != null) {
|
||||
configConsumer
|
||||
.accept(SkeletonConfigOffsets.TORSO, chestOffset + hipOffset + waistOffset);
|
||||
}
|
||||
|
||||
if (chestOffset != null) {
|
||||
configConsumer.accept(SkeletonConfigOffsets.CHEST, chestOffset);
|
||||
}
|
||||
|
||||
if (hipOffset != null) {
|
||||
configConsumer.accept(SkeletonConfigOffsets.WAIST, hipOffset);
|
||||
}
|
||||
|
||||
Float hipWidthOffset = offsets.get(BoneType.LEFT_HIP);
|
||||
if (hipWidthOffset == null) {
|
||||
hipWidthOffset = offsets.get(BoneType.RIGHT_HIP);
|
||||
}
|
||||
if (hipWidthOffset != null) {
|
||||
configConsumer
|
||||
.accept(SkeletonConfigOffsets.HIPS_WIDTH, hipWidthOffset * 2f);
|
||||
}
|
||||
|
||||
Float upperLegOffset = offsets.get(BoneType.LEFT_UPPER_LEG);
|
||||
if (upperLegOffset == null) {
|
||||
upperLegOffset = offsets.get(BoneType.RIGHT_UPPER_LEG);
|
||||
}
|
||||
Float lowerLegOffset = offsets.get(BoneType.LEFT_LOWER_LEG);
|
||||
if (lowerLegOffset == null) {
|
||||
lowerLegOffset = offsets.get(BoneType.RIGHT_LOWER_LEG);
|
||||
}
|
||||
if (upperLegOffset != null && lowerLegOffset != null) {
|
||||
configConsumer
|
||||
.accept(SkeletonConfigOffsets.LEGS_LENGTH, upperLegOffset + lowerLegOffset);
|
||||
}
|
||||
|
||||
if (lowerLegOffset != null) {
|
||||
configConsumer.accept(SkeletonConfigOffsets.KNEE_HEIGHT, lowerLegOffset);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean applyConfig(BiConsumer<SkeletonConfigOffsets, Float> configConsumer) {
|
||||
return applyConfig(configConsumer, offsets);
|
||||
}
|
||||
|
||||
public boolean applyConfig(
|
||||
Map<SkeletonConfigOffsets, Float> skeletonConfig,
|
||||
Map<BoneType, Float> offsets
|
||||
) {
|
||||
if (skeletonConfig == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return applyConfig(skeletonConfig::put, offsets);
|
||||
}
|
||||
|
||||
public boolean applyConfig(Map<SkeletonConfigOffsets, Float> skeletonConfig) {
|
||||
return applyConfig(skeletonConfig, offsets);
|
||||
}
|
||||
|
||||
public boolean applyConfig(SkeletonConfig skeletonConfig, Map<BoneType, Float> offsets) {
|
||||
if (skeletonConfig == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return applyConfig(skeletonConfig::setOffset, offsets);
|
||||
}
|
||||
|
||||
public boolean applyConfig(SkeletonConfig skeletonConfig) {
|
||||
return applyConfig(skeletonConfig, offsets);
|
||||
}
|
||||
|
||||
public boolean applyAndSaveConfig(Skeleton skeleton) {
|
||||
if (skeleton == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
SkeletonConfig skeletonConfig = skeleton.getSkeletonConfig();
|
||||
if (!applyConfig(skeletonConfig))
|
||||
return false;
|
||||
|
||||
skeletonConfig.save();
|
||||
server.getConfigManager().saveConfig();
|
||||
|
||||
LogManager.info("[AutoBone] Configured skeleton bone lengths");
|
||||
return true;
|
||||
}
|
||||
|
||||
public Float getConfig(BoneType config) {
|
||||
return offsets.get(config);
|
||||
}
|
||||
|
||||
public <T> float sumSelectConfigs(
|
||||
List<T> selection,
|
||||
Function<T, Float> configs
|
||||
) {
|
||||
float sum = 0f;
|
||||
|
||||
for (T config : selection) {
|
||||
Float length = configs.apply(config);
|
||||
if (length != null) {
|
||||
sum += length;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
public <T> float sumSelectConfigs(
|
||||
List<T> selection,
|
||||
Map<T, Float> configs
|
||||
) {
|
||||
return sumSelectConfigs(selection, configs::get);
|
||||
}
|
||||
|
||||
public float sumSelectConfigs(
|
||||
List<SkeletonConfigOffsets> selection,
|
||||
SkeletonConfig config
|
||||
) {
|
||||
return sumSelectConfigs(selection, config::getOffset);
|
||||
}
|
||||
|
||||
public float getLengthSum(Map<BoneType, Float> configs) {
|
||||
return getLengthSum(configs, null);
|
||||
}
|
||||
|
||||
public float getLengthSum(
|
||||
Map<BoneType, Float> configs,
|
||||
Map<BoneType, Float> configsAlt
|
||||
) {
|
||||
float length = 0f;
|
||||
|
||||
if (configsAlt != null) {
|
||||
for (Entry<BoneType, Float> config : configsAlt.entrySet()) {
|
||||
// If there isn't a duplicate config
|
||||
if (!configs.containsKey(config.getKey())) {
|
||||
length += config.getValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (Float boneLength : configs.values()) {
|
||||
length += boneLength;
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
public float getTargetHeight(PoseFrames frames) {
|
||||
float targetHeight;
|
||||
// Get the current skeleton from the server
|
||||
Skeleton skeleton = getSkeleton();
|
||||
if (skeleton != null) {
|
||||
// If there is a skeleton available, calculate the target height
|
||||
// from its configs
|
||||
targetHeight = sumSelectConfigs(legacyHeightConfigs, skeleton.getSkeletonConfig());
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Target height loaded from skeleton (Make sure you reset before running!): "
|
||||
+ targetHeight
|
||||
);
|
||||
} else {
|
||||
// Otherwise if there is no skeleton available, attempt to get the
|
||||
// max HMD height from the recording
|
||||
float hmdHeight = frames.getMaxHmdHeight();
|
||||
if (hmdHeight <= 0.50f) {
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Max headset height detected (Value seems too low, did you not stand up straight while measuring?): "
|
||||
+ hmdHeight
|
||||
);
|
||||
} else {
|
||||
LogManager.info("[AutoBone] Max headset height detected: " + hmdHeight);
|
||||
}
|
||||
|
||||
// Estimate target height from HMD height
|
||||
targetHeight = hmdHeight;
|
||||
}
|
||||
|
||||
return targetHeight;
|
||||
}
|
||||
|
||||
public AutoBoneResults processFrames(PoseFrames frames, Consumer<Epoch> epochCallback)
|
||||
throws AutoBoneException {
|
||||
return processFrames(frames, -1f, epochCallback);
|
||||
}
|
||||
|
||||
public AutoBoneResults processFrames(
|
||||
PoseFrames frames,
|
||||
float targetHeight,
|
||||
Consumer<Epoch> epochCallback
|
||||
) throws AutoBoneException {
|
||||
return processFrames(frames, true, targetHeight, epochCallback);
|
||||
}
|
||||
|
||||
public AutoBoneResults processFrames(
|
||||
PoseFrames frames,
|
||||
boolean calcInitError,
|
||||
float targetHeight,
|
||||
Consumer<Epoch> epochCallback
|
||||
) throws AutoBoneException {
|
||||
final int frameCount = frames.getMaxFrameCount();
|
||||
|
||||
List<PoseFrameTracker> trackers = frames.getTrackers();
|
||||
reloadConfigValues(trackers); // Reload configs and detect chest tracker
|
||||
// from the first frame
|
||||
|
||||
final PoseFrameSkeleton skeleton1 = new PoseFrameSkeleton(
|
||||
trackers,
|
||||
null
|
||||
);
|
||||
final PoseFrameSkeleton skeleton2 = new PoseFrameSkeleton(
|
||||
trackers,
|
||||
null
|
||||
);
|
||||
|
||||
EnumMap<BoneType, Float> intermediateOffsets = new EnumMap<>(
|
||||
offsets
|
||||
);
|
||||
|
||||
AutoBoneTrainingStep trainingStep = new AutoBoneTrainingStep(
|
||||
targetHeight,
|
||||
skeleton1,
|
||||
skeleton2,
|
||||
frames,
|
||||
intermediateOffsets
|
||||
);
|
||||
|
||||
skeleton1.setLegTweaksEnabled(false);
|
||||
skeleton2.setLegTweaksEnabled(false);
|
||||
|
||||
// If target height isn't specified, auto-detect
|
||||
if (targetHeight < 0f) {
|
||||
targetHeight = getTargetHeight(frames);
|
||||
}
|
||||
|
||||
StatsCalculator errorStats = new StatsCalculator();
|
||||
|
||||
// Epoch loop, each epoch is one full iteration over the full dataset
|
||||
for (int epoch = calcInitError ? -1 : 0; epoch < this.config.numEpochs; epoch++) {
|
||||
float adjustRate = epoch >= 0
|
||||
? (this.config.initialAdjustRate
|
||||
* FastMath.pow(this.config.adjustRateMultiplier, epoch))
|
||||
: 0f;
|
||||
|
||||
int[] randomFrameIndices = null;
|
||||
if (config.randomizeFrameOrder) {
|
||||
randomFrameIndices = new int[frameCount];
|
||||
|
||||
int zeroPos = -1;
|
||||
for (int i = 0; i < frameCount; i++) {
|
||||
int index = rand.nextInt(frameCount);
|
||||
|
||||
if (i > 0) {
|
||||
while (index == zeroPos || randomFrameIndices[index] > 0) {
|
||||
index = rand.nextInt(frameCount);
|
||||
}
|
||||
} else {
|
||||
zeroPos = index;
|
||||
}
|
||||
|
||||
randomFrameIndices[index] = i;
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate over the frames using a cursor and an offset for
|
||||
// comparing frames a
|
||||
// certain number of frames apart
|
||||
for (
|
||||
int cursorOffset = this.config.minDataDistance;
|
||||
cursorOffset <= this.config.maxDataDistance
|
||||
&& cursorOffset < frameCount;
|
||||
cursorOffset++
|
||||
) {
|
||||
for (
|
||||
int frameCursor = 0; frameCursor < frameCount - cursorOffset;
|
||||
frameCursor += config.cursorIncrement
|
||||
) {
|
||||
int frameCursor2 = frameCursor + cursorOffset;
|
||||
|
||||
applyConfig(skeleton1.skeletonConfig);
|
||||
skeleton2.skeletonConfig.setConfigs(skeleton1.skeletonConfig);
|
||||
|
||||
if (config.randomizeFrameOrder) {
|
||||
trainingStep
|
||||
.setCursors(
|
||||
randomFrameIndices[frameCursor],
|
||||
randomFrameIndices[frameCursor2]
|
||||
);
|
||||
} else {
|
||||
trainingStep.setCursors(frameCursor, frameCursor2);
|
||||
}
|
||||
|
||||
skeleton1.setCursor(trainingStep.getCursor1());
|
||||
skeleton2.setCursor(trainingStep.getCursor2());
|
||||
|
||||
skeleton1.updatePose();
|
||||
skeleton2.updatePose();
|
||||
|
||||
float totalLength = getLengthSum(offsets);
|
||||
float curHeight = sumSelectConfigs(heightOffsets, offsets);
|
||||
trainingStep.setCurrentHeight(curHeight);
|
||||
|
||||
float errorDeriv = getErrorDeriv(trainingStep);
|
||||
float error = errorFunc(errorDeriv);
|
||||
|
||||
// In case of fire
|
||||
if (Float.isNaN(error) || Float.isInfinite(error)) {
|
||||
// Extinguish
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Error value is invalid, resetting variables to recover"
|
||||
);
|
||||
reloadConfigValues(trackers);
|
||||
|
||||
// Reset error sum values
|
||||
errorStats.reset();
|
||||
|
||||
// Continue on new data
|
||||
continue;
|
||||
}
|
||||
|
||||
// Store the error count for logging purposes
|
||||
errorStats.addValue(errorDeriv);
|
||||
|
||||
float adjustVal = error * adjustRate;
|
||||
|
||||
// If there is no adjustment whatsoever, skip this
|
||||
if (adjustVal == 0f) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Vector3f slideLeft = skeleton2
|
||||
.getComputedTracker(TrackerRole.LEFT_FOOT).position
|
||||
.subtract(
|
||||
skeleton1.getComputedTracker(TrackerRole.LEFT_FOOT).position
|
||||
);
|
||||
|
||||
Vector3f slideRight = skeleton2
|
||||
.getComputedTracker(TrackerRole.RIGHT_FOOT).position
|
||||
.subtract(
|
||||
skeleton1
|
||||
.getComputedTracker(TrackerRole.RIGHT_FOOT).position
|
||||
);
|
||||
|
||||
intermediateOffsets.putAll(offsets);
|
||||
for (Entry<BoneType, Float> entry : offsets.entrySet()) {
|
||||
// Skip adjustment if the epoch is before starting (for
|
||||
// logging only)
|
||||
if (epoch < 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
float originalLength = entry.getValue();
|
||||
boolean isHeightVar = heightOffsets.contains(entry.getKey());
|
||||
|
||||
float leftDotProduct = getDotProductDiff(
|
||||
skeleton1,
|
||||
skeleton2,
|
||||
entry.getKey(),
|
||||
false,
|
||||
slideLeft
|
||||
);
|
||||
|
||||
float rightDotProduct = getDotProductDiff(
|
||||
skeleton1,
|
||||
skeleton2,
|
||||
entry.getKey(),
|
||||
true,
|
||||
slideRight
|
||||
);
|
||||
|
||||
float dotLength = originalLength
|
||||
* ((leftDotProduct + rightDotProduct) / 2f);
|
||||
|
||||
// Scale by the ratio for smooth adjustment and more
|
||||
// stable results
|
||||
float curAdjustVal = (adjustVal * -dotLength) / totalLength;
|
||||
float newLength = originalLength + curAdjustVal;
|
||||
|
||||
// No small or negative numbers!!! Bad algorithm!
|
||||
if (newLength < 0.01f) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Apply new offset length
|
||||
intermediateOffsets.put(entry.getKey(), newLength);
|
||||
applyConfig(skeleton1.skeletonConfig, intermediateOffsets);
|
||||
skeleton2.skeletonConfig.setConfigs(skeleton1.skeletonConfig);
|
||||
|
||||
// Update the skeleton poses for the new offset length
|
||||
skeleton1.updatePose();
|
||||
skeleton2.updatePose();
|
||||
|
||||
float newHeight = isHeightVar ? curHeight + curAdjustVal : curHeight;
|
||||
trainingStep.setCurrentHeight(newHeight);
|
||||
|
||||
float newErrorDeriv = getErrorDeriv(trainingStep);
|
||||
|
||||
if (newErrorDeriv < errorDeriv) {
|
||||
entry.setValue(newLength);
|
||||
}
|
||||
|
||||
// Reset the length to minimize bias in other variables,
|
||||
// it's applied later
|
||||
intermediateOffsets.put(entry.getKey(), originalLength);
|
||||
applyConfig(skeleton1.skeletonConfig, intermediateOffsets);
|
||||
skeleton2.skeletonConfig.setConfigs(skeleton1.skeletonConfig);
|
||||
}
|
||||
|
||||
if (config.scaleEachStep) {
|
||||
float stepHeight = sumSelectConfigs(heightOffsets, offsets);
|
||||
|
||||
if (stepHeight > 0f) {
|
||||
float stepHeightDiff = targetHeight - stepHeight;
|
||||
for (Entry<BoneType, Float> entry : offsets.entrySet()) {
|
||||
// Only height variables
|
||||
if (
|
||||
entry.getKey() == BoneType.NECK
|
||||
|| !heightOffsets.contains(entry.getKey())
|
||||
)
|
||||
continue;
|
||||
|
||||
float length = entry.getValue();
|
||||
|
||||
// Multiply the diff by the length to height
|
||||
// ratio
|
||||
float adjVal = stepHeightDiff * (length / stepHeight);
|
||||
|
||||
// Scale the length to fit the target height
|
||||
entry.setValue(Math.max(length + (adjVal / 2f), 0.01f));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average error over the epoch
|
||||
if (
|
||||
epoch <= 0
|
||||
|| epoch >= (config.numEpochs - 1)
|
||||
|| (epoch + 1) % config.printEveryNumEpochs == 0
|
||||
) {
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Epoch "
|
||||
+ (epoch + 1)
|
||||
+ " average error: "
|
||||
+ errorStats.getMean()
|
||||
+ " (SD "
|
||||
+ errorStats.getStandardDeviation()
|
||||
+ ")"
|
||||
);
|
||||
}
|
||||
|
||||
applyConfig(legacyConfigs);
|
||||
if (epochCallback != null) {
|
||||
epochCallback
|
||||
.accept(new Epoch(epoch + 1, this.config.numEpochs, errorStats, legacyConfigs));
|
||||
}
|
||||
}
|
||||
|
||||
float finalHeight = sumSelectConfigs(heightOffsets, offsets);
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Target height: "
|
||||
+ targetHeight
|
||||
+ " New height: "
|
||||
+ finalHeight
|
||||
);
|
||||
|
||||
return new AutoBoneResults(finalHeight, targetHeight, errorStats, legacyConfigs);
|
||||
}
|
||||
|
||||
protected float getErrorDeriv(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
float sumError = 0f;
|
||||
|
||||
if (this.config.slideErrorFactor > 0f) {
|
||||
sumError += slideError.getStepError(trainingStep) * this.config.slideErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.offsetSlideErrorFactor > 0f) {
|
||||
sumError += offsetSlideError.getStepError(trainingStep)
|
||||
* this.config.offsetSlideErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.footHeightOffsetErrorFactor > 0f) {
|
||||
sumError += footHeightOffsetError.getStepError(trainingStep)
|
||||
* this.config.footHeightOffsetErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.bodyProportionErrorFactor > 0f) {
|
||||
sumError += bodyProportionError.getStepError(trainingStep)
|
||||
* this.config.bodyProportionErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.heightErrorFactor > 0f) {
|
||||
sumError += heightError.getStepError(trainingStep) * this.config.heightErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.positionErrorFactor > 0f) {
|
||||
sumError += positionError.getStepError(trainingStep)
|
||||
* this.config.positionErrorFactor;
|
||||
}
|
||||
|
||||
if (this.config.positionOffsetErrorFactor > 0f) {
|
||||
sumError += positionOffsetError.getStepError(trainingStep)
|
||||
* this.config.positionOffsetErrorFactor;
|
||||
}
|
||||
|
||||
return sumError;
|
||||
}
|
||||
|
||||
public String getLengthsString() {
|
||||
final StringBuilder configInfo = new StringBuilder();
|
||||
this.offsets.forEach((key, value) -> {
|
||||
if (configInfo.length() > 0) {
|
||||
configInfo.append(", ");
|
||||
}
|
||||
|
||||
configInfo
|
||||
.append(key.toString())
|
||||
.append(": ")
|
||||
.append(StringUtils.prettyNumber(value * 100f, 2));
|
||||
});
|
||||
|
||||
return configInfo.toString();
|
||||
}
|
||||
|
||||
public void saveRecording(PoseFrames frames, File recordingFile) {
|
||||
if (saveDir.isDirectory() || saveDir.mkdirs()) {
|
||||
LogManager
|
||||
.info("[AutoBone] Exporting frames to \"" + recordingFile.getPath() + "\"...");
|
||||
if (PoseFrameIO.writeToFile(recordingFile, frames)) {
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Done exporting! Recording can be found at \""
|
||||
+ recordingFile.getPath()
|
||||
+ "\"."
|
||||
);
|
||||
} else {
|
||||
LogManager
|
||||
.severe(
|
||||
"[AutoBone] Failed to export the recording to \""
|
||||
+ recordingFile.getPath()
|
||||
+ "\"."
|
||||
);
|
||||
}
|
||||
} else {
|
||||
LogManager
|
||||
.severe(
|
||||
"[AutoBone] Failed to create the recording directory \""
|
||||
+ saveDir.getPath()
|
||||
+ "\"."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public void saveRecording(PoseFrames frames, String recordingFileName) {
|
||||
saveRecording(frames, new File(saveDir, recordingFileName));
|
||||
}
|
||||
|
||||
public void saveRecording(PoseFrames frames) {
|
||||
File recordingFile;
|
||||
int recordingIndex = 1;
|
||||
do {
|
||||
recordingFile = new File(saveDir, "ABRecording" + recordingIndex++ + ".pfr");
|
||||
} while (recordingFile.exists());
|
||||
|
||||
saveRecording(frames, recordingFile);
|
||||
}
|
||||
|
||||
public List<Pair<String, PoseFrames>> loadRecordings() {
|
||||
List<Pair<String, PoseFrames>> recordings = new FastList<>();
|
||||
if (loadDir.isDirectory()) {
|
||||
File[] files = loadDir.listFiles();
|
||||
if (files != null) {
|
||||
for (File file : files) {
|
||||
if (
|
||||
file.isFile()
|
||||
&& org.apache.commons.lang3.StringUtils
|
||||
.endsWithIgnoreCase(file.getName(), ".pfr")
|
||||
) {
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Detected recording at \""
|
||||
+ file.getPath()
|
||||
+ "\", loading frames..."
|
||||
);
|
||||
PoseFrames frames = PoseFrameIO.readFromFile(file);
|
||||
|
||||
if (frames == null) {
|
||||
LogManager
|
||||
.severe("Reading frames from \"" + file.getPath() + "\" failed...");
|
||||
} else {
|
||||
recordings.add(Pair.of(file.getName(), frames));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return recordings;
|
||||
}
|
||||
|
||||
public AutoBoneConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public class Epoch {
|
||||
|
||||
public final int epoch;
|
||||
public final int totalEpochs;
|
||||
public final StatsCalculator epochError;
|
||||
public final EnumMap<SkeletonConfigOffsets, Float> configValues;
|
||||
|
||||
public Epoch(
|
||||
int epoch,
|
||||
int totalEpochs,
|
||||
StatsCalculator epochError,
|
||||
EnumMap<SkeletonConfigOffsets, Float> configValues
|
||||
) {
|
||||
this.epoch = epoch;
|
||||
this.totalEpochs = totalEpochs;
|
||||
this.epochError = epochError;
|
||||
this.configValues = configValues;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Epoch: " + epoch + ", Epoch Error: " + epochError;
|
||||
}
|
||||
}
|
||||
|
||||
public class AutoBoneResults {
|
||||
|
||||
public final float finalHeight;
|
||||
public final float targetHeight;
|
||||
public final StatsCalculator epochError;
|
||||
public final EnumMap<SkeletonConfigOffsets, Float> configValues;
|
||||
|
||||
public AutoBoneResults(
|
||||
float finalHeight,
|
||||
float targetHeight,
|
||||
StatsCalculator epochError,
|
||||
EnumMap<SkeletonConfigOffsets, Float> configValues
|
||||
) {
|
||||
this.finalHeight = finalHeight;
|
||||
this.targetHeight = targetHeight;
|
||||
this.epochError = epochError;
|
||||
this.configValues = configValues;
|
||||
}
|
||||
|
||||
public float getHeightDifference() {
|
||||
return FastMath.abs(targetHeight - finalHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package dev.slimevr.autobone;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.autobone.AutoBone.AutoBoneResults;
|
||||
import dev.slimevr.autobone.errors.AutoBoneException;
|
||||
import dev.slimevr.poserecorder.PoseFrameTracker;
|
||||
import dev.slimevr.poserecorder.PoseFrames;
|
||||
import dev.slimevr.poserecorder.PoseRecorder;
|
||||
import dev.slimevr.poserecorder.TrackerFrame;
|
||||
import dev.slimevr.poserecorder.TrackerFrameData;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfig;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
|
||||
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<AutoBoneListener> 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 AutoBoneResults processFrames(PoseFrames frames) throws AutoBoneException {
|
||||
return autoBone
|
||||
.processFrames(
|
||||
frames,
|
||||
autoBone.getConfig().calcInitError,
|
||||
autoBone.getConfig().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 = this.autoBone.getConfig().sampleCount;
|
||||
long sampleRate = this.autoBone.getConfig().sampleRateMs;
|
||||
Future<PoseFrames> framesFuture = poseRecorder
|
||||
.startFrameRecording(
|
||||
sampleCount,
|
||||
sampleRate,
|
||||
progress -> announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
progress.frame,
|
||||
progress.totalFrames
|
||||
)
|
||||
);
|
||||
PoseFrames frames = framesFuture.get();
|
||||
LogManager.info("[AutoBone] Done recording!");
|
||||
|
||||
// Save a recurring recording for users to send as debug info
|
||||
announceProcessStatus(AutoBoneProcessType.RECORD, "Saving recording...");
|
||||
autoBone.saveRecording(frames, "LastABRecording.pfr");
|
||||
|
||||
if (this.autoBone.getConfig().saveRecordings) {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
"Saving recording (from config option)..."
|
||||
);
|
||||
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<PoseFrames> 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<Pair<String, PoseFrames>> frameRecordings = autoBone.loadRecordings();
|
||||
|
||||
if (!frameRecordings.isEmpty()) {
|
||||
LogManager.info("[AutoBone] Done loading frames!");
|
||||
} else {
|
||||
Future<PoseFrames> 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("<Recording>", 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...");
|
||||
StatsCalculator errorStats = new StatsCalculator();
|
||||
SkeletonConfig skeletonConfigBuffer = new SkeletonConfig(false);
|
||||
for (Pair<String, PoseFrames> recording : frameRecordings) {
|
||||
LogManager
|
||||
.info("[AutoBone] Processing frames from \"" + recording.getKey() + "\"...");
|
||||
|
||||
List<PoseFrameTracker> trackers = recording.getValue().getTrackers();
|
||||
|
||||
StringBuilder trackerInfo = new StringBuilder();
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
if (tracker == null)
|
||||
continue;
|
||||
|
||||
TrackerFrame frame = tracker.safeGetFrame(0);
|
||||
if (frame == null || !frame.hasData(TrackerFrameData.DESIGNATION))
|
||||
continue;
|
||||
|
||||
if (trackerInfo.length() > 0) {
|
||||
trackerInfo.append(", ");
|
||||
}
|
||||
|
||||
trackerInfo.append(frame.designation.designation);
|
||||
|
||||
if (frame.hasData(TrackerFrameData.POSITION)) {
|
||||
trackerInfo.append(" (P)");
|
||||
}
|
||||
}
|
||||
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] ("
|
||||
+ trackers.size()
|
||||
+ " trackers) ["
|
||||
+ trackerInfo
|
||||
+ "]"
|
||||
);
|
||||
|
||||
AutoBoneResults autoBoneResults = processFrames(recording.getValue());
|
||||
errorStats.addValue(autoBoneResults.getHeightDifference());
|
||||
LogManager.info("[AutoBone] Done processing!");
|
||||
|
||||
// #region Stats/Values
|
||||
skeletonConfigBuffer.setConfigs(autoBoneResults.configValues, null, null);
|
||||
|
||||
float neckLength = skeletonConfigBuffer.getOffset(SkeletonConfigOffsets.NECK);
|
||||
float chestDistance = skeletonConfigBuffer
|
||||
.getOffset(SkeletonConfigOffsets.CHEST);
|
||||
float torsoLength = skeletonConfigBuffer
|
||||
.getOffset(SkeletonConfigOffsets.TORSO);
|
||||
float hipWidth = skeletonConfigBuffer
|
||||
.getOffset(SkeletonConfigOffsets.HIPS_WIDTH);
|
||||
float legsLength = skeletonConfigBuffer
|
||||
.getOffset(SkeletonConfigOffsets.LEGS_LENGTH);
|
||||
float kneeHeight = skeletonConfigBuffer
|
||||
.getOffset(SkeletonConfigOffsets.KNEE_HEIGHT);
|
||||
|
||||
float neckTorso = neckLength / torsoLength;
|
||||
float chestTorso = chestDistance / torsoLength;
|
||||
float torsoWaist = hipWidth / torsoLength;
|
||||
float legTorso = legsLength / torsoLength;
|
||||
float legBody = legsLength / (torsoLength + neckLength);
|
||||
float kneeLeg = kneeHeight / legsLength;
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Average height error: "
|
||||
+ StringUtils.prettyNumber(errorStats.getMean(), 6)
|
||||
+ " (SD "
|
||||
+ StringUtils.prettyNumber(errorStats.getStandardDeviation(), 6)
|
||||
+ ")"
|
||||
);
|
||||
// #endregion
|
||||
|
||||
listeners.forEach(listener -> listener.onAutoBoneEnd(autoBone.legacyConfigs));
|
||||
|
||||
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.applyAndSaveConfig();
|
||||
announceProcessStatus(AutoBoneProcessType.APPLY, "Adjusted values applied!", true, true);
|
||||
// TODO Update GUI values after applying? Is that needed here?
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.SkeletonConfigOffsets;
|
||||
|
||||
|
||||
public interface AutoBoneListener {
|
||||
|
||||
void onAutoBoneProcessStatus(
|
||||
AutoBoneProcessType processType,
|
||||
String message,
|
||||
long current,
|
||||
long total,
|
||||
boolean completed,
|
||||
boolean success
|
||||
);
|
||||
|
||||
void onAutoBoneRecordingEnd(PoseFrames recording);
|
||||
|
||||
void onAutoBoneEpoch(Epoch epoch);
|
||||
|
||||
void onAutoBoneEnd(EnumMap<SkeletonConfigOffsets, Float> configValues);
|
||||
}
|
||||
@@ -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<Integer, AutoBoneProcessType> byId = new HashMap<>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dev.slimevr.autobone;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import dev.slimevr.poserecorder.PoseFrameSkeleton;
|
||||
import dev.slimevr.poserecorder.PoseFrames;
|
||||
import dev.slimevr.vr.processor.skeleton.BoneType;
|
||||
|
||||
|
||||
public class AutoBoneTrainingStep {
|
||||
private int cursor1 = 0;
|
||||
private int cursor2 = 0;
|
||||
|
||||
private float currentHeight;
|
||||
private final float targetHeight;
|
||||
|
||||
private final PoseFrameSkeleton skeleton1;
|
||||
private final PoseFrameSkeleton skeleton2;
|
||||
|
||||
private final PoseFrames trainingFrames;
|
||||
|
||||
private final Map<BoneType, Float> intermediateOffsets;
|
||||
|
||||
public AutoBoneTrainingStep(
|
||||
int cursor1,
|
||||
int cursor2,
|
||||
float targetHeight,
|
||||
PoseFrameSkeleton skeleton1,
|
||||
PoseFrameSkeleton skeleton2,
|
||||
PoseFrames trainingFrames,
|
||||
Map<BoneType, Float> intermediateOffsets
|
||||
) {
|
||||
this.cursor1 = cursor1;
|
||||
this.cursor2 = cursor2;
|
||||
this.targetHeight = targetHeight;
|
||||
this.skeleton1 = skeleton1;
|
||||
this.skeleton2 = skeleton2;
|
||||
this.trainingFrames = trainingFrames;
|
||||
this.intermediateOffsets = intermediateOffsets;
|
||||
}
|
||||
|
||||
public AutoBoneTrainingStep(
|
||||
float targetHeight,
|
||||
PoseFrameSkeleton skeleton1,
|
||||
PoseFrameSkeleton skeleton2,
|
||||
PoseFrames trainingFrames,
|
||||
Map<BoneType, Float> intermediateOffsets
|
||||
) {
|
||||
this.targetHeight = targetHeight;
|
||||
this.skeleton1 = skeleton1;
|
||||
this.skeleton2 = skeleton2;
|
||||
this.trainingFrames = trainingFrames;
|
||||
this.intermediateOffsets = intermediateOffsets;
|
||||
}
|
||||
|
||||
public int getCursor1() {
|
||||
return cursor1;
|
||||
}
|
||||
|
||||
public void setCursor1(int cursor1) {
|
||||
this.cursor1 = cursor1;
|
||||
}
|
||||
|
||||
public int getCursor2() {
|
||||
return cursor2;
|
||||
}
|
||||
|
||||
public void setCursor2(int cursor2) {
|
||||
this.cursor2 = cursor2;
|
||||
}
|
||||
|
||||
public void setCursors(int cursor1, int cursor2) {
|
||||
this.cursor1 = cursor1;
|
||||
this.cursor2 = cursor2;
|
||||
}
|
||||
|
||||
public float getCurrentHeight() {
|
||||
return currentHeight;
|
||||
}
|
||||
|
||||
public void setCurrentHeight(float currentHeight) {
|
||||
this.currentHeight = currentHeight;
|
||||
}
|
||||
|
||||
public float getTargetHeight() {
|
||||
return targetHeight;
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton getSkeleton1() {
|
||||
return skeleton1;
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton getSkeleton2() {
|
||||
return skeleton2;
|
||||
}
|
||||
|
||||
public PoseFrames getTrainingFrames() {
|
||||
return trainingFrames;
|
||||
}
|
||||
|
||||
public Map<BoneType, Float> getIntermediateOffsets() {
|
||||
return intermediateOffsets;
|
||||
}
|
||||
|
||||
public float getHeightOffset() {
|
||||
return getTargetHeight() - getCurrentHeight();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dev.slimevr.autobone;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
|
||||
/// This is a stat calculator based on Welford's online algorithm
|
||||
/// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
|
||||
public class StatsCalculator {
|
||||
|
||||
private int count = 0;
|
||||
private float mean = 0f;
|
||||
private float M2 = 0f;
|
||||
|
||||
public void reset() {
|
||||
count = 0;
|
||||
mean = 0f;
|
||||
M2 = 0f;
|
||||
}
|
||||
|
||||
public void addValue(float newValue) {
|
||||
count += 1;
|
||||
float delta = newValue - mean;
|
||||
mean += delta / count;
|
||||
float delta2 = newValue - mean;
|
||||
M2 += delta * delta2;
|
||||
}
|
||||
|
||||
public float getMean() {
|
||||
return mean;
|
||||
}
|
||||
|
||||
public float getVariance() {
|
||||
if (count < 1) {
|
||||
return Float.NaN;
|
||||
}
|
||||
|
||||
return M2 / count;
|
||||
}
|
||||
|
||||
public float getSampleVariance() {
|
||||
if (count < 2) {
|
||||
return Float.NaN;
|
||||
}
|
||||
|
||||
return M2 / (count - 1);
|
||||
}
|
||||
|
||||
public float getStandardDeviation() {
|
||||
return FastMath.sqrt(getVariance());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
public class AutoBoneException extends Exception {
|
||||
|
||||
public AutoBoneException() {
|
||||
}
|
||||
|
||||
public AutoBoneException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AutoBoneException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public AutoBoneException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public AutoBoneException(
|
||||
String message,
|
||||
Throwable cause,
|
||||
boolean enableSuppression,
|
||||
boolean writableStackTrace
|
||||
) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.autobone.errors.proportions.ProportionLimiter;
|
||||
import dev.slimevr.autobone.errors.proportions.RangeProportionLimiter;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfig;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
|
||||
|
||||
// The distance from average human proportions
|
||||
public class BodyProportionError implements IAutoBoneError {
|
||||
|
||||
// TODO hip tracker stuff... Hip tracker should be around 3 to 5
|
||||
// centimeters.
|
||||
|
||||
// The headset height is not the full height! This value compensates for the
|
||||
// offset from the headset height to the user height
|
||||
public float eyeHeightToHeightRatio = 0.936f;
|
||||
|
||||
// Default config
|
||||
// Height: 1.58
|
||||
// Full Height: 1.58 / 0.936 = 1.688034
|
||||
// Neck: 0.1 / 1.688034 = 0.059241
|
||||
// Torso: 0.56 / 1.688034 = 0.331747
|
||||
// Chest: 0.32 / 1.688034 = 0.18957
|
||||
// Waist: (0.56 - 0.32 - 0.04) / 1.688034 = 0.118481
|
||||
// Hip: 0.04 / 1.688034 = 0.023696
|
||||
// Hip Width: 0.26 / 1.688034 = 0.154025
|
||||
// Upper Leg: (0.92 - 0.50) / 1.688034 = 0.24881
|
||||
// Lower Leg: 0.50 / 1.688034 = 0.296203
|
||||
|
||||
// "Expected" are values from Drillis and Contini (1966)
|
||||
// "Experimental" are values from experimentation by the SlimeVR community
|
||||
public static final ProportionLimiter[] proportionLimits = new ProportionLimiter[] {
|
||||
// Head
|
||||
// Experimental: 0.059
|
||||
new RangeProportionLimiter(0.059f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.HEAD);
|
||||
}, 0.01f),
|
||||
|
||||
// Neck
|
||||
// Expected: 0.052
|
||||
// Experimental: 0.059
|
||||
new RangeProportionLimiter(0.054f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.NECK);
|
||||
}, 0.0015f),
|
||||
|
||||
// Torso
|
||||
// Expected: 0.288 (0.333 including hip, this shouldn't be right...)
|
||||
new RangeProportionLimiter(0.333f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.TORSO);
|
||||
}, 0.015f),
|
||||
|
||||
// Chest
|
||||
// Experimental: 0.189
|
||||
new RangeProportionLimiter(0.189f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.CHEST);
|
||||
}, 0.02f),
|
||||
|
||||
// Waist
|
||||
// Experimental: 0.118
|
||||
new RangeProportionLimiter(0.118f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.TORSO)
|
||||
- config.getOffset(SkeletonConfigOffsets.CHEST)
|
||||
- config.getOffset(SkeletonConfigOffsets.WAIST);
|
||||
}, 0.05f),
|
||||
|
||||
// Hip
|
||||
// Experimental: 0.0237
|
||||
new RangeProportionLimiter(0.0237f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.WAIST);
|
||||
}, 0.01f),
|
||||
|
||||
// Hip Width
|
||||
// Expected: 0.191
|
||||
// Experimental: 0.154
|
||||
new RangeProportionLimiter(0.184f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.HIPS_WIDTH);
|
||||
}, 0.04f),
|
||||
|
||||
// Upper Leg
|
||||
// Expected: 0.245
|
||||
new RangeProportionLimiter(0.245f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.LEGS_LENGTH)
|
||||
- config.getOffset(SkeletonConfigOffsets.KNEE_HEIGHT);
|
||||
}, 0.015f),
|
||||
|
||||
// Lower Leg
|
||||
// Expected: 0.246 (0.285 including below ankle, could use a separate
|
||||
// offset?)
|
||||
new RangeProportionLimiter(0.285f, config -> {
|
||||
return config.getOffset(SkeletonConfigOffsets.KNEE_HEIGHT);
|
||||
}, 0.02f),
|
||||
};
|
||||
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
return getBodyProportionError(
|
||||
trainingStep.getSkeleton1().skeletonConfig,
|
||||
trainingStep.getCurrentHeight()
|
||||
);
|
||||
}
|
||||
|
||||
public float getBodyProportionError(SkeletonConfig config, float height) {
|
||||
float fullHeight = height / eyeHeightToHeightRatio;
|
||||
|
||||
float sum = 0f;
|
||||
for (ProportionLimiter limiter : proportionLimits) {
|
||||
sum += FastMath.abs(limiter.getProportionError(config, fullHeight));
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.trackers.ComputedTracker;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
|
||||
|
||||
// The offset between the height both feet at one instant and over time
|
||||
public class FootHeightOffsetError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
return getSlideError(trainingStep.getSkeleton1(), trainingStep.getSkeleton2());
|
||||
}
|
||||
|
||||
public static float getSlideError(HumanSkeleton skeleton1, HumanSkeleton skeleton2) {
|
||||
ComputedTracker leftTracker1 = skeleton1.getComputedTracker(TrackerRole.LEFT_FOOT);
|
||||
ComputedTracker rightTracker1 = skeleton1.getComputedTracker(TrackerRole.RIGHT_FOOT);
|
||||
|
||||
ComputedTracker leftTracker2 = skeleton2.getComputedTracker(TrackerRole.LEFT_FOOT);
|
||||
ComputedTracker rightTracker2 = skeleton2.getComputedTracker(TrackerRole.RIGHT_FOOT);
|
||||
|
||||
return getFootHeightError(leftTracker1, rightTracker1, leftTracker2, rightTracker2);
|
||||
}
|
||||
|
||||
public static float getFootHeightError(
|
||||
ComputedTracker leftTracker1,
|
||||
ComputedTracker rightTracker1,
|
||||
ComputedTracker leftTracker2,
|
||||
ComputedTracker rightTracker2
|
||||
) {
|
||||
float leftFoot1 = leftTracker1.position.y;
|
||||
float rightFoot1 = rightTracker1.position.y;
|
||||
|
||||
float leftFoot2 = leftTracker2.position.y;
|
||||
float rightFoot2 = rightTracker2.position.y;
|
||||
|
||||
// Compute all combinations of heights
|
||||
float dist1 = FastMath.abs(leftFoot1 - rightFoot1);
|
||||
float dist2 = FastMath.abs(leftFoot1 - leftFoot2);
|
||||
float dist3 = FastMath.abs(leftFoot1 - rightFoot2);
|
||||
|
||||
float dist4 = FastMath.abs(rightFoot1 - leftFoot2);
|
||||
float dist5 = FastMath.abs(rightFoot1 - rightFoot2);
|
||||
|
||||
float dist6 = FastMath.abs(leftFoot2 - rightFoot2);
|
||||
|
||||
// Divide by 12 (6 values * 2 to halve) to halve and average, it's
|
||||
// halved because you want to approach a midpoint, not the other point
|
||||
return (dist1 + dist2 + dist3 + dist4 + dist5 + dist6) / 12f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
|
||||
|
||||
// The difference from the current height to the target height
|
||||
public class HeightError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
return getHeightError(
|
||||
trainingStep.getCurrentHeight(),
|
||||
trainingStep.getTargetHeight()
|
||||
);
|
||||
}
|
||||
|
||||
public float getHeightError(float currentHeight, float targetHeight) {
|
||||
return FastMath.abs(targetHeight - currentHeight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
|
||||
|
||||
public interface IAutoBoneError {
|
||||
float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import com.jme3.math.Vector3f;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.trackers.ComputedTracker;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
|
||||
|
||||
// The change in distance between both of the ankles over time
|
||||
public class OffsetSlideError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
return getSlideError(trainingStep.getSkeleton1(), trainingStep.getSkeleton2());
|
||||
}
|
||||
|
||||
public static float getSlideError(HumanSkeleton skeleton1, HumanSkeleton skeleton2) {
|
||||
ComputedTracker leftTracker1 = skeleton1.getComputedTracker(TrackerRole.LEFT_FOOT);
|
||||
ComputedTracker rightTracker1 = skeleton1.getComputedTracker(TrackerRole.RIGHT_FOOT);
|
||||
|
||||
ComputedTracker leftTracker2 = skeleton2.getComputedTracker(TrackerRole.LEFT_FOOT);
|
||||
ComputedTracker rightTracker2 = skeleton2.getComputedTracker(TrackerRole.RIGHT_FOOT);
|
||||
|
||||
return getSlideError(leftTracker1, rightTracker1, leftTracker2, rightTracker2);
|
||||
}
|
||||
|
||||
public static float getSlideError(
|
||||
ComputedTracker leftTracker1,
|
||||
ComputedTracker rightTracker1,
|
||||
ComputedTracker leftTracker2,
|
||||
ComputedTracker rightTracker2
|
||||
) {
|
||||
Vector3f leftFoot1 = leftTracker1.position;
|
||||
Vector3f rightFoot1 = rightTracker1.position;
|
||||
|
||||
Vector3f leftFoot2 = leftTracker2.position;
|
||||
Vector3f rightFoot2 = rightTracker2.position;
|
||||
|
||||
float slideDist1 = leftFoot1.distance(rightFoot1);
|
||||
float slideDist2 = leftFoot2.distance(rightFoot2);
|
||||
|
||||
float slideDist3 = leftFoot1.distance(rightFoot2);
|
||||
float slideDist4 = leftFoot2.distance(rightFoot1);
|
||||
|
||||
// Compute all combinations of distances
|
||||
float dist1 = FastMath.abs(slideDist1 - slideDist2);
|
||||
float dist2 = FastMath.abs(slideDist1 - slideDist3);
|
||||
float dist3 = FastMath.abs(slideDist1 - slideDist4);
|
||||
|
||||
float dist4 = FastMath.abs(slideDist2 - slideDist3);
|
||||
float dist5 = FastMath.abs(slideDist2 - slideDist4);
|
||||
|
||||
float dist6 = FastMath.abs(slideDist3 - slideDist4);
|
||||
|
||||
// Divide by 12 (6 values * 2 to halve) to halve and average, it's
|
||||
// halved because you want to approach a midpoint, not the other point
|
||||
return (dist1 + dist2 + dist3 + dist4 + dist5 + dist6) / 12f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.poserecorder.PoseFrameTracker;
|
||||
import dev.slimevr.poserecorder.TrackerFrame;
|
||||
import dev.slimevr.poserecorder.TrackerFrameData;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.trackers.ComputedTracker;
|
||||
|
||||
|
||||
// The distance of any points to the corresponding absolute position
|
||||
public class PositionError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
List<PoseFrameTracker> trackers = trainingStep.getTrainingFrames().getTrackers();
|
||||
return (getPositionError(
|
||||
trackers,
|
||||
trainingStep.getCursor1(),
|
||||
trainingStep.getSkeleton1()
|
||||
)
|
||||
+ getPositionError(
|
||||
trackers,
|
||||
trainingStep.getCursor2(),
|
||||
trainingStep.getSkeleton2()
|
||||
))
|
||||
/ 2f;
|
||||
}
|
||||
|
||||
public static float getPositionError(
|
||||
List<PoseFrameTracker> trackers,
|
||||
int cursor,
|
||||
HumanSkeleton skeleton
|
||||
) {
|
||||
float offset = 0f;
|
||||
int offsetCount = 0;
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
TrackerFrame trackerFrame = tracker.safeGetFrame(cursor);
|
||||
if (
|
||||
trackerFrame == null
|
||||
|| !trackerFrame.hasData(TrackerFrameData.POSITION)
|
||||
|| !trackerFrame.hasData(TrackerFrameData.DESIGNATION)
|
||||
|| trackerFrame.designation.trackerRole.isEmpty()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ComputedTracker computedTracker = skeleton
|
||||
.getComputedTracker(trackerFrame.designation.trackerRole.get());
|
||||
if (computedTracker != null) {
|
||||
offset += FastMath.abs(computedTracker.position.distance(trackerFrame.position));
|
||||
offsetCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return offsetCount > 0 ? offset / offsetCount : 0f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.poserecorder.PoseFrameTracker;
|
||||
import dev.slimevr.poserecorder.TrackerFrame;
|
||||
import dev.slimevr.poserecorder.TrackerFrameData;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.trackers.ComputedTracker;
|
||||
|
||||
|
||||
// The difference between offset of absolute position and the corresponding point over time
|
||||
public class PositionOffsetError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
List<PoseFrameTracker> trackers = trainingStep.getTrainingFrames().getTrackers();
|
||||
return getPositionOffsetError(
|
||||
trackers,
|
||||
trainingStep.getCursor1(),
|
||||
trainingStep.getCursor2(),
|
||||
trainingStep.getSkeleton1(),
|
||||
trainingStep.getSkeleton2()
|
||||
);
|
||||
}
|
||||
|
||||
public float getPositionOffsetError(
|
||||
List<PoseFrameTracker> trackers,
|
||||
int cursor1,
|
||||
int cursor2,
|
||||
HumanSkeleton skeleton1,
|
||||
HumanSkeleton skeleton2
|
||||
) {
|
||||
float offset = 0f;
|
||||
int offsetCount = 0;
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
TrackerFrame trackerFrame1 = tracker.safeGetFrame(cursor1);
|
||||
if (
|
||||
trackerFrame1 == null
|
||||
|| !trackerFrame1.hasData(TrackerFrameData.POSITION)
|
||||
|| !trackerFrame1.hasData(TrackerFrameData.DESIGNATION)
|
||||
|| trackerFrame1.designation.trackerRole.isEmpty()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
TrackerFrame trackerFrame2 = tracker.safeGetFrame(cursor2);
|
||||
if (
|
||||
trackerFrame2 == null
|
||||
|| !trackerFrame2.hasData(TrackerFrameData.POSITION)
|
||||
|| !trackerFrame2.hasData(TrackerFrameData.DESIGNATION)
|
||||
|| trackerFrame2.designation.trackerRole.isEmpty()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ComputedTracker computedTracker1 = skeleton1
|
||||
.getComputedTracker(trackerFrame1.designation.trackerRole.get());
|
||||
if (computedTracker1 == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ComputedTracker computedTracker2 = skeleton2
|
||||
.getComputedTracker(trackerFrame2.designation.trackerRole.get());
|
||||
if (computedTracker2 == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
float dist1 = FastMath.abs(computedTracker1.position.distance(trackerFrame1.position));
|
||||
float dist2 = FastMath.abs(computedTracker2.position.distance(trackerFrame2.position));
|
||||
|
||||
offset += FastMath.abs(dist2 - dist1);
|
||||
offsetCount++;
|
||||
}
|
||||
|
||||
return offsetCount > 0 ? offset / offsetCount : 0f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.slimevr.autobone.errors;
|
||||
|
||||
import dev.slimevr.autobone.AutoBoneTrainingStep;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.trackers.ComputedTracker;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
|
||||
|
||||
// The change in position of the ankle over time
|
||||
public class SlideError implements IAutoBoneError {
|
||||
@Override
|
||||
public float getStepError(AutoBoneTrainingStep trainingStep) throws AutoBoneException {
|
||||
return getSlideError(trainingStep.getSkeleton1(), trainingStep.getSkeleton2());
|
||||
}
|
||||
|
||||
public static float getSlideError(HumanSkeleton skeleton1, HumanSkeleton skeleton2) {
|
||||
// Calculate and average between both feet
|
||||
return (getSlideError(skeleton1, skeleton2, TrackerRole.LEFT_FOOT)
|
||||
+ getSlideError(skeleton1, skeleton2, TrackerRole.RIGHT_FOOT)) / 2f;
|
||||
}
|
||||
|
||||
public static float getSlideError(
|
||||
HumanSkeleton skeleton1,
|
||||
HumanSkeleton skeleton2,
|
||||
TrackerRole trackerRole
|
||||
) {
|
||||
// Calculate and average between both feet
|
||||
return getSlideError(
|
||||
skeleton1.getComputedTracker(trackerRole),
|
||||
skeleton2.getComputedTracker(trackerRole)
|
||||
);
|
||||
}
|
||||
|
||||
public static float getSlideError(ComputedTracker tracker1, ComputedTracker tracker2) {
|
||||
// Return the midpoint distance
|
||||
return tracker1.position.distance(tracker2.position) / 2f;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dev.slimevr.autobone.errors.proportions;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfig;
|
||||
|
||||
|
||||
public class HardProportionLimiter implements ProportionLimiter {
|
||||
|
||||
protected final float targetRatio;
|
||||
protected final Function<SkeletonConfig, Float> boneLengthFunction;
|
||||
|
||||
/**
|
||||
* @param targetRatio The bone to height ratio to target
|
||||
* @param boneLengthFunction A function that takes a SkeletonConfig object
|
||||
* and returns the bone length
|
||||
*/
|
||||
public HardProportionLimiter(
|
||||
float targetRatio,
|
||||
Function<SkeletonConfig, Float> boneLengthFunction
|
||||
) {
|
||||
this.targetRatio = targetRatio;
|
||||
this.boneLengthFunction = boneLengthFunction;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getProportionError(SkeletonConfig config, float height) {
|
||||
float boneLength = boneLengthFunction.apply(config);
|
||||
return targetRatio - (boneLength / height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.slimevr.autobone.errors.proportions;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfig;
|
||||
|
||||
|
||||
public interface ProportionLimiter {
|
||||
public float getProportionError(SkeletonConfig config, float height);
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package dev.slimevr.autobone.errors.proportions;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfig;
|
||||
|
||||
|
||||
public class RangeProportionLimiter extends HardProportionLimiter {
|
||||
|
||||
protected final float targetPositiveRange;
|
||||
protected final float targetNegativeRange;
|
||||
|
||||
/**
|
||||
* @param targetRatio The bone to height ratio to target
|
||||
* @param boneLengthFunction A function that takes a SkeletonConfig object
|
||||
* and returns the bone length
|
||||
* @param range The range from the target ratio to accept (ex. 0.1)
|
||||
*/
|
||||
public RangeProportionLimiter(
|
||||
float targetRatio,
|
||||
Function<SkeletonConfig, Float> boneLengthFunction,
|
||||
float range
|
||||
) {
|
||||
super(targetRatio, boneLengthFunction);
|
||||
|
||||
// Handle if someone puts in a negative value
|
||||
range = FastMath.abs(range);
|
||||
targetPositiveRange = range;
|
||||
targetNegativeRange = -range;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param targetRatio The bone to height ratio to target
|
||||
* @param boneLengthFunction A function that takes a SkeletonConfig object
|
||||
* and returns the bone length
|
||||
* @param positiveRange The positive range from the target ratio to accept
|
||||
* (ex. 0.1)
|
||||
* @param negativeRange The negative range from the target ratio to accept
|
||||
* (ex. -0.1)
|
||||
*/
|
||||
public RangeProportionLimiter(
|
||||
float targetRatio,
|
||||
Function<SkeletonConfig, Float> boneLengthFunction,
|
||||
float positiveRange,
|
||||
float negativeRange
|
||||
) {
|
||||
super(targetRatio, boneLengthFunction);
|
||||
|
||||
// If the positive range is less than the negative range, something is
|
||||
// wrong
|
||||
if (positiveRange < negativeRange) {
|
||||
throw new IllegalArgumentException("positiveRange must not be less than negativeRange");
|
||||
}
|
||||
|
||||
targetPositiveRange = positiveRange;
|
||||
targetNegativeRange = negativeRange;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getProportionError(SkeletonConfig config, float height) {
|
||||
float boneLength = boneLengthFunction.apply(config);
|
||||
float ratioOffset = targetRatio - (boneLength / height);
|
||||
|
||||
// If the range is exceeded, return the offset from the range limit
|
||||
if (ratioOffset > targetPositiveRange) {
|
||||
return ratioOffset - targetPositiveRange;
|
||||
} else if (ratioOffset < targetNegativeRange) {
|
||||
return ratioOffset - targetNegativeRange;
|
||||
}
|
||||
|
||||
return 0f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.trackers.ShareableTracker;
|
||||
|
||||
|
||||
/**
|
||||
* Bridge handles sending and receiving tracker data between SlimeVR and other
|
||||
* systems like VR APIs (SteamVR, OpenXR, etc), apps and protocols (VMC,
|
||||
* WebSocket, TIP). It can create and manage tracker received from the <b>remote
|
||||
* side</b> or send shared <b>local trackers</b> to the other side.
|
||||
*/
|
||||
public interface Bridge {
|
||||
|
||||
@VRServerThread
|
||||
void dataRead();
|
||||
|
||||
@VRServerThread
|
||||
void dataWrite();
|
||||
|
||||
/**
|
||||
* Adds shared tracker to the bridge. Bridge should notify the other side of
|
||||
* this tracker, if it's the type of tracker this bridge serves, and start
|
||||
* sending data each update
|
||||
*
|
||||
* @param tracker
|
||||
*/
|
||||
@VRServerThread
|
||||
void addSharedTracker(ShareableTracker tracker);
|
||||
|
||||
/**
|
||||
* Removes tracker from a bridge. If the other side supports tracker
|
||||
* removal, bridge should notify it and stop sending new data. If it doesn't
|
||||
* support tracker removal, the bridge can either stop sending new data, or
|
||||
* keep sending it if it's available.
|
||||
*
|
||||
* @param tracker
|
||||
*/
|
||||
@VRServerThread
|
||||
void removeSharedTracker(ShareableTracker tracker);
|
||||
|
||||
@VRServerThread
|
||||
void startBridge();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
|
||||
@Retention(value = RetentionPolicy.SOURCE)
|
||||
public @interface BridgeThread {
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.trackers.ShareableTracker;
|
||||
|
||||
|
||||
public class OpenVRNativeBridge implements Bridge {
|
||||
|
||||
public OpenVRNativeBridge() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataRead() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataWrite() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void startBridge() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
public enum PipeState {
|
||||
CREATED,
|
||||
OPEN,
|
||||
ERROR
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.Main;
|
||||
import dev.slimevr.bridge.ProtobufMessages.TrackerStatus;
|
||||
import dev.slimevr.bridge.ProtobufMessages.*;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.trackers.*;
|
||||
import io.eiren.util.ann.Synchronize;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
|
||||
public abstract class ProtobufBridge<T extends VRTracker> implements Bridge {
|
||||
|
||||
@VRServerThread
|
||||
protected final List<ShareableTracker> sharedTrackers = new FastList<>();
|
||||
protected final String bridgeName;
|
||||
private final Vector3f vec1 = new Vector3f();
|
||||
private final Quaternion quat1 = new Quaternion();
|
||||
@ThreadSafe
|
||||
private final Queue<ProtobufMessage> inputQueue = new LinkedBlockingQueue<>();
|
||||
@ThreadSafe
|
||||
private final Queue<ProtobufMessage> outputQueue = new LinkedBlockingQueue<>();
|
||||
@Synchronize("self")
|
||||
private final Map<String, T> remoteTrackersBySerial = new HashMap<>();
|
||||
@Synchronize("self")
|
||||
private final Map<Integer, T> remoteTrackersByTrackerId = new HashMap<>();
|
||||
private final HMDTracker hmd;
|
||||
private boolean hadNewData = false;
|
||||
private T hmdTracker;
|
||||
|
||||
public ProtobufBridge(String bridgeName, HMDTracker hmd) {
|
||||
this.bridgeName = bridgeName;
|
||||
this.hmd = hmd;
|
||||
}
|
||||
|
||||
@BridgeThread
|
||||
protected abstract boolean sendMessageReal(ProtobufMessage message);
|
||||
|
||||
@BridgeThread
|
||||
protected void messageReceived(ProtobufMessage message) {
|
||||
inputQueue.add(message);
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
protected void sendMessage(ProtobufMessage message) {
|
||||
outputQueue.add(message);
|
||||
}
|
||||
|
||||
@BridgeThread
|
||||
protected void updateMessageQueue() {
|
||||
ProtobufMessage message = null;
|
||||
while ((message = outputQueue.poll()) != null) {
|
||||
if (!sendMessageReal(message))
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
@Override
|
||||
public void dataRead() {
|
||||
hadNewData = false;
|
||||
ProtobufMessage message = null;
|
||||
while ((message = inputQueue.poll()) != null) {
|
||||
processMessageReceived(message);
|
||||
hadNewData = true;
|
||||
}
|
||||
if (hadNewData && hmdTracker != null) {
|
||||
trackerOverrideUpdate(hmdTracker, hmd);
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void trackerOverrideUpdate(T source, ComputedTracker target) {
|
||||
target.position.set(source.position);
|
||||
target.rotation.set(source.rotation);
|
||||
target.setStatus(source.getStatus());
|
||||
target.dataTick();
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
@Override
|
||||
public void dataWrite() {
|
||||
if (!hadNewData) // Don't write anything if no message were received, we
|
||||
// always process at the
|
||||
// speed of the other side
|
||||
return;
|
||||
for (ShareableTracker tracker : sharedTrackers) {
|
||||
writeTrackerUpdate(tracker);
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void writeTrackerUpdate(ShareableTracker localTracker) {
|
||||
Position.Builder builder = Position.newBuilder().setTrackerId(localTracker.getTrackerId());
|
||||
if (localTracker.getPosition(vec1)) {
|
||||
builder.setX(vec1.x);
|
||||
builder.setY(vec1.y);
|
||||
builder.setZ(vec1.z);
|
||||
}
|
||||
if (localTracker.getRotation(quat1)) {
|
||||
builder.setQx(quat1.getX());
|
||||
builder.setQy(quat1.getY());
|
||||
builder.setQz(quat1.getZ());
|
||||
builder.setQw(quat1.getW());
|
||||
}
|
||||
sendMessage(ProtobufMessage.newBuilder().setPosition(builder).build());
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void processMessageReceived(ProtobufMessage message) {
|
||||
// if(!message.hasPosition())
|
||||
// LogManager.log.info("[" + bridgeName + "] MSG: " + message);
|
||||
if (message.hasPosition()) {
|
||||
positionReceived(message.getPosition());
|
||||
} else if (message.hasUserAction()) {
|
||||
userActionReceived(message.getUserAction());
|
||||
} else if (message.hasTrackerStatus()) {
|
||||
trackerStatusReceived(message.getTrackerStatus());
|
||||
} else if (message.hasTrackerAdded()) {
|
||||
trackerAddedReceived(message.getTrackerAdded());
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void positionReceived(Position positionMessage) {
|
||||
T tracker = getInternalRemoteTrackerById(positionMessage.getTrackerId());
|
||||
if (tracker != null) {
|
||||
if (positionMessage.hasX())
|
||||
tracker.position
|
||||
.set(positionMessage.getX(), positionMessage.getY(), positionMessage.getZ());
|
||||
tracker.rotation
|
||||
.set(
|
||||
positionMessage.getQx(),
|
||||
positionMessage.getQy(),
|
||||
positionMessage.getQz(),
|
||||
positionMessage.getQw()
|
||||
);
|
||||
tracker.dataTick();
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected abstract T createNewTracker(TrackerAdded trackerAdded);
|
||||
|
||||
@VRServerThread
|
||||
protected void trackerAddedReceived(TrackerAdded trackerAdded) {
|
||||
T tracker = getInternalRemoteTrackerById(trackerAdded.getTrackerId());
|
||||
if (tracker != null) {
|
||||
// TODO reinit?
|
||||
return;
|
||||
}
|
||||
tracker = createNewTracker(trackerAdded);
|
||||
synchronized (remoteTrackersBySerial) {
|
||||
remoteTrackersBySerial.put(tracker.getName(), tracker);
|
||||
}
|
||||
synchronized (remoteTrackersByTrackerId) {
|
||||
remoteTrackersByTrackerId.put(tracker.getTrackerId(), tracker);
|
||||
}
|
||||
if (trackerAdded.getTrackerRole() == TrackerRole.HMD.id) {
|
||||
hmdTracker = tracker;
|
||||
} else {
|
||||
Main.vrServer.registerTracker(tracker);
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void userActionReceived(UserAction userAction) {
|
||||
switch (userAction.getName()) {
|
||||
case "calibrate":
|
||||
LogManager
|
||||
.warning("[" + bridgeName + "] Received deprecated user action 'calibrate'!");
|
||||
case "reset":
|
||||
// TODO : Check pose field
|
||||
Main.vrServer.resetTrackers();
|
||||
break;
|
||||
case "fast_reset":
|
||||
Main.vrServer.resetTrackersYaw();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void trackerStatusReceived(TrackerStatus trackerStatus) {
|
||||
T tracker = getInternalRemoteTrackerById(trackerStatus.getTrackerId());
|
||||
if (tracker != null) {
|
||||
tracker
|
||||
.setStatus(
|
||||
dev.slimevr.vr.trackers.TrackerStatus.getById(trackerStatus.getStatusValue())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
protected T getInternalRemoteTrackerById(int trackerId) {
|
||||
synchronized (remoteTrackersByTrackerId) {
|
||||
return remoteTrackersByTrackerId.get(trackerId);
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void reconnected() {
|
||||
for (ShareableTracker tracker : sharedTrackers) {
|
||||
TrackerAdded.Builder builder = TrackerAdded
|
||||
.newBuilder()
|
||||
.setTrackerId(tracker.getTrackerId())
|
||||
.setTrackerName(tracker.getName())
|
||||
.setTrackerSerial(tracker.getName())
|
||||
.setTrackerRole(tracker.getTrackerRole().id);
|
||||
sendMessage(ProtobufMessage.newBuilder().setTrackerAdded(builder).build());
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
protected void disconnected() {
|
||||
synchronized (remoteTrackersByTrackerId) {
|
||||
for (Entry<Integer, T> integerTEntry : remoteTrackersByTrackerId.entrySet()) {
|
||||
integerTEntry
|
||||
.getValue()
|
||||
.setStatus(dev.slimevr.vr.trackers.TrackerStatus.DISCONNECTED);
|
||||
}
|
||||
}
|
||||
if (hmdTracker != null) {
|
||||
hmd.setStatus(dev.slimevr.vr.trackers.TrackerStatus.DISCONNECTED);
|
||||
}
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
@Override
|
||||
public void addSharedTracker(ShareableTracker tracker) {
|
||||
if (sharedTrackers.contains(tracker))
|
||||
return;
|
||||
sharedTrackers.add(tracker);
|
||||
TrackerAdded.Builder builder = TrackerAdded
|
||||
.newBuilder()
|
||||
.setTrackerId(tracker.getTrackerId())
|
||||
.setTrackerName(tracker.getName())
|
||||
.setTrackerSerial(tracker.getName())
|
||||
.setTrackerRole(tracker.getTrackerRole().id);
|
||||
sendMessage(ProtobufMessage.newBuilder().setTrackerAdded(builder).build());
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
@Override
|
||||
public void removeSharedTracker(ShareableTracker tracker) {
|
||||
// Remove shared tracker
|
||||
sharedTrackers.remove(tracker);
|
||||
|
||||
// Set the tracker's status as disconnected
|
||||
TrackerStatus.Builder statusBuilder = TrackerStatus
|
||||
.newBuilder()
|
||||
.setTrackerId(tracker.getTrackerId());
|
||||
statusBuilder.setStatus(TrackerStatus.Status.DISCONNECTED);
|
||||
sendMessage(ProtobufMessage.newBuilder().setTrackerStatus(statusBuilder).build());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,51 @@
|
||||
package dev.slimevr.bridge;
|
||||
|
||||
import dev.slimevr.vr.trackers.ShareableTracker;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
|
||||
public class VMCBridge extends Thread implements Bridge {
|
||||
|
||||
public final int readPort;
|
||||
public final int writePort;
|
||||
public final InetAddress writeAddr;
|
||||
|
||||
public VMCBridge(int readPort, int writePort, InetAddress writeAddr) {
|
||||
super("Virtual Motion Capture bridge");
|
||||
if (readPort == writePort)
|
||||
throw new IllegalArgumentException("Read and write port shouldn't be the same!");
|
||||
this.readPort = readPort;
|
||||
this.writePort = writePort;
|
||||
this.writeAddr = writeAddr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataRead() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataWrite() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startBridge() {
|
||||
start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
public class AutoBoneConfig {
|
||||
|
||||
public int cursorIncrement = 2;
|
||||
public int minDataDistance = 1;
|
||||
public int maxDataDistance = 1;
|
||||
|
||||
public int numEpochs = 100;
|
||||
|
||||
public int printEveryNumEpochs = 25;
|
||||
|
||||
public float initialAdjustRate = 10f;
|
||||
public float adjustRateMultiplier = 0.995f;
|
||||
|
||||
public float slideErrorFactor = 0.0f;
|
||||
public float offsetSlideErrorFactor = 2.0f;
|
||||
public float footHeightOffsetErrorFactor = 0.0f;
|
||||
public float bodyProportionErrorFactor = 0.825f;
|
||||
public float heightErrorFactor = 0.0f;
|
||||
public float positionErrorFactor = 0.0f;
|
||||
public float positionOffsetErrorFactor = 0.0f;
|
||||
|
||||
public boolean calcInitError = false;
|
||||
public float targetHeight = -1;
|
||||
|
||||
public boolean randomizeFrameOrder = true;
|
||||
public boolean scaleEachStep = true;
|
||||
|
||||
public int sampleCount = 1000;
|
||||
public long sampleRateMs = 20;
|
||||
|
||||
public boolean saveRecordings = false;
|
||||
|
||||
public AutoBoneConfig() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdKeySerializers;
|
||||
import dev.slimevr.config.serializers.BooleanMapDeserializer;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class BridgeConfig {
|
||||
|
||||
@JsonDeserialize(using = BooleanMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
public Map<String, Boolean> trackers = new HashMap<>();
|
||||
|
||||
public BridgeConfig() {
|
||||
}
|
||||
|
||||
public boolean getBridgeTrackerRole(TrackerRole role, boolean def) {
|
||||
return trackers.getOrDefault(role.name().toLowerCase(), def);
|
||||
}
|
||||
|
||||
public void setBridgeTrackerRole(TrackerRole role, boolean val) {
|
||||
this.trackers.put(role.name().toLowerCase(), val);
|
||||
}
|
||||
|
||||
public Map<String, Boolean> getTrackers() {
|
||||
return trackers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.github.jonpeterson.jackson.module.versioning.VersioningModule;
|
||||
import com.jme3.math.Quaternion;
|
||||
import dev.slimevr.config.serializers.QuaternionDeserializer;
|
||||
import dev.slimevr.config.serializers.QuaternionSerializer;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
|
||||
public class ConfigManager {
|
||||
|
||||
private final String configPath;
|
||||
|
||||
private final ObjectMapper om;
|
||||
|
||||
private VRConfig vrConfig;
|
||||
|
||||
|
||||
public ConfigManager(String configPath) {
|
||||
this.configPath = configPath;
|
||||
om = new ObjectMapper(new YAMLFactory());
|
||||
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
om.registerModule(new VersioningModule());
|
||||
SimpleModule quaternionModule = new SimpleModule();
|
||||
quaternionModule.addSerializer(Quaternion.class, new QuaternionSerializer());
|
||||
quaternionModule.addDeserializer(Quaternion.class, new QuaternionDeserializer());
|
||||
om.registerModule(quaternionModule);
|
||||
}
|
||||
|
||||
public void loadConfig() {
|
||||
try {
|
||||
this.vrConfig = om
|
||||
.readValue(new FileInputStream(configPath), VRConfig.class);
|
||||
} catch (FileNotFoundException e) {
|
||||
// Config file didn't exist, is not an error
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
if (this.vrConfig == null) {
|
||||
this.vrConfig = new VRConfig();
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public synchronized void saveConfig() {
|
||||
File cfgFile = new File(configPath);
|
||||
|
||||
try {
|
||||
om.writeValue(cfgFile, this.vrConfig);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public VRConfig getVrConfig() {
|
||||
return vrConfig;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.DoubleNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.github.jonpeterson.jackson.module.versioning.VersionedModelConverter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class CurrentVRConfigConverter implements VersionedModelConverter {
|
||||
|
||||
@Override
|
||||
public ObjectNode convert(
|
||||
ObjectNode modelData,
|
||||
String modelVersion,
|
||||
String targetModelVersion,
|
||||
JsonNodeFactory nodeFactory
|
||||
) {
|
||||
|
||||
int version = Integer.parseInt(modelVersion);
|
||||
|
||||
// Configs less than version 2 need a migration to the latest config
|
||||
if (version < 2) {
|
||||
// Move zoom to the window config
|
||||
ObjectNode windowNode = (ObjectNode) modelData.get("window");
|
||||
DoubleNode zoomNode = (DoubleNode) modelData.get("zoom");
|
||||
if (windowNode != null && zoomNode != null) {
|
||||
windowNode.set("zoom", zoomNode);
|
||||
modelData.remove("zoom");
|
||||
}
|
||||
|
||||
// Change trackers list to map
|
||||
ArrayNode oldTrackersNode = modelData.withArray("trackers");
|
||||
if (oldTrackersNode != null) {
|
||||
var trackersIter = oldTrackersNode.iterator();
|
||||
ObjectNode trackersNode = nodeFactory.objectNode();
|
||||
while (trackersIter.hasNext()) {
|
||||
JsonNode node = trackersIter.next();
|
||||
JsonNode resultNode = TrackerConfig.toV2(node, nodeFactory);
|
||||
trackersNode.set(node.get("name").asText(), resultNode);
|
||||
}
|
||||
modelData.set("trackers", trackersNode);
|
||||
}
|
||||
|
||||
// Rename bridge to bridges
|
||||
ObjectNode bridgeNode = (ObjectNode) modelData.get("bridge");
|
||||
if (bridgeNode != null) {
|
||||
modelData.set("bridges", bridgeNode);
|
||||
modelData.remove("bridge");
|
||||
}
|
||||
|
||||
// Move body to skeleton (and merge it to current skeleton)
|
||||
ObjectNode bodyNode = (ObjectNode) modelData.get("body");
|
||||
if (bodyNode != null) {
|
||||
var bodyIter = bodyNode.fields();
|
||||
ObjectNode skeletonNode = (ObjectNode) modelData.get("skeleton");
|
||||
if (skeletonNode == null) {
|
||||
skeletonNode = nodeFactory.objectNode();
|
||||
}
|
||||
|
||||
ObjectNode offsetsNode = nodeFactory.objectNode();
|
||||
while (bodyIter.hasNext()) {
|
||||
Map.Entry<String, JsonNode> node = bodyIter.next();
|
||||
// Filter only number values because other types would be
|
||||
// stuff
|
||||
// that didn't get migrated correctly before
|
||||
if (node.getValue().isNumber()) {
|
||||
offsetsNode.set(node.getKey(), node.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
// Fix calibration wolf typos
|
||||
offsetsNode.set("shouldersWidth", bodyNode.get("shoulersWidth"));
|
||||
offsetsNode.set("shouldersDistance", bodyNode.get("shoulersDistance"));
|
||||
offsetsNode.remove("shoulersWidth");
|
||||
offsetsNode.remove("shoulersDistance");
|
||||
skeletonNode.set("offsets", offsetsNode);
|
||||
modelData.set("skeleton", skeletonNode);
|
||||
modelData.remove("body");
|
||||
}
|
||||
}
|
||||
|
||||
return modelData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import dev.slimevr.Main;
|
||||
import dev.slimevr.filtering.TrackerFilters;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import dev.slimevr.vr.trackers.TrackerWithFiltering;
|
||||
|
||||
|
||||
public class FiltersConfig {
|
||||
|
||||
// Type of filtering applied (none, smoothing or prediction)
|
||||
private String type = "prediction";
|
||||
|
||||
// Amount/Intensity of the specified filtering (0 to 1)
|
||||
private float amount = 0.2f;
|
||||
|
||||
public FiltersConfig() {
|
||||
}
|
||||
|
||||
public void updateTrackersFilters() {
|
||||
for (Tracker t : Main.vrServer.getAllTrackers()) {
|
||||
Tracker tracker = t.get();
|
||||
if (tracker instanceof TrackerWithFiltering) {
|
||||
((TrackerWithFiltering) tracker)
|
||||
.setFiltering(
|
||||
enumGetType(),
|
||||
getAmount()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TrackerFilters enumGetType() {
|
||||
return TrackerFilters.getByConfigkey(type);
|
||||
}
|
||||
|
||||
public void enumSetType(TrackerFilters type) {
|
||||
this.type = type.configKey;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public float getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(float amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
public class KeybindingsConfig {
|
||||
|
||||
private String resetBinding = "CTRL+ALT+SHIFT+Y";
|
||||
|
||||
private String quickResetBinding = "CTRL+ALT+SHIFT+U";
|
||||
|
||||
public KeybindingsConfig() {
|
||||
}
|
||||
|
||||
public String getResetBinding() {
|
||||
return resetBinding;
|
||||
}
|
||||
|
||||
public String getQuickResetBinding() {
|
||||
return quickResetBinding;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
public class OverlayConfig {
|
||||
|
||||
private boolean isMirrored = false;
|
||||
private boolean isVisible = false;
|
||||
|
||||
|
||||
public boolean isMirrored() {
|
||||
return isMirrored;
|
||||
}
|
||||
|
||||
public boolean isVisible() {
|
||||
return isVisible;
|
||||
}
|
||||
|
||||
public void setMirrored(boolean mirrored) {
|
||||
isMirrored = mirrored;
|
||||
}
|
||||
|
||||
public void setVisible(boolean visible) {
|
||||
isVisible = visible;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdKeySerializers;
|
||||
import dev.slimevr.config.serializers.BooleanMapDeserializer;
|
||||
import dev.slimevr.config.serializers.FloatMapDeserializer;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class SkeletonConfig {
|
||||
|
||||
@JsonDeserialize(using = BooleanMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
public Map<String, Boolean> toggles = new HashMap<>();
|
||||
|
||||
@JsonDeserialize(using = FloatMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
public Map<String, Float> values = new HashMap<>();
|
||||
|
||||
@JsonDeserialize(using = FloatMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
public Map<String, Float> offsets = new HashMap<>();
|
||||
|
||||
public Map<String, Boolean> getToggles() {
|
||||
return toggles;
|
||||
}
|
||||
|
||||
public Map<String, Float> getOffsets() {
|
||||
return offsets;
|
||||
}
|
||||
|
||||
public Map<String, Float> getValues() {
|
||||
return values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.jme3.math.Quaternion;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
|
||||
|
||||
public class TrackerConfig {
|
||||
|
||||
private String customName;
|
||||
private String designation;
|
||||
private boolean hide;
|
||||
|
||||
private Quaternion adjustment;
|
||||
|
||||
private Quaternion mountingRotation;
|
||||
|
||||
public TrackerConfig() {
|
||||
}
|
||||
|
||||
public TrackerConfig(Tracker tracker) {
|
||||
this.designation = tracker.getBodyPosition()
|
||||
!= null ? tracker.getBodyPosition().designation : null;
|
||||
this.customName = tracker.getCustomName();
|
||||
}
|
||||
|
||||
static JsonNode toV2(JsonNode v1, JsonNodeFactory factory) {
|
||||
ObjectNode node = factory.objectNode();
|
||||
if (v1.has("customName"))
|
||||
node.set("customName", v1.get("customName"));
|
||||
if (v1.has("designation"))
|
||||
node.set("designation", v1.get("designation"));
|
||||
if (v1.has("hide"))
|
||||
node.set("hide", v1.get("hide"));
|
||||
if (v1.has("mountingRotation"))
|
||||
node.set("mountingRotation", v1.get("mountingRotation"));
|
||||
if (v1.has("adjustment"))
|
||||
node.set("adjustment", v1.get("adjustment"));
|
||||
return node;
|
||||
}
|
||||
|
||||
public String getCustomName() {
|
||||
return customName;
|
||||
}
|
||||
|
||||
public void setCustomName(String customName) {
|
||||
this.customName = customName;
|
||||
}
|
||||
|
||||
public String getDesignation() {
|
||||
return designation;
|
||||
}
|
||||
|
||||
public void setDesignation(String designation) {
|
||||
this.designation = designation;
|
||||
}
|
||||
|
||||
public boolean isHide() {
|
||||
return hide;
|
||||
}
|
||||
|
||||
public void setHide(boolean hide) {
|
||||
this.hide = hide;
|
||||
}
|
||||
|
||||
public Quaternion getAdjustment() {
|
||||
return adjustment;
|
||||
}
|
||||
|
||||
public void setAdjustment(Quaternion adjustment) {
|
||||
this.adjustment = adjustment;
|
||||
}
|
||||
|
||||
public Quaternion getMountingRotation() {
|
||||
return mountingRotation;
|
||||
}
|
||||
|
||||
public void setMountingRotation(Quaternion mountingRotation) {
|
||||
this.mountingRotation = mountingRotation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdKeySerializers;
|
||||
import com.github.jonpeterson.jackson.module.versioning.JsonVersionedModel;
|
||||
import dev.slimevr.config.serializers.BridgeConfigMapDeserializer;
|
||||
import dev.slimevr.config.serializers.TrackerConfigMapDeserializer;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@JsonVersionedModel(
|
||||
currentVersion = "2", defaultDeserializeToVersion = "1", toCurrentConverterClass = CurrentVRConfigConverter.class
|
||||
)
|
||||
public class VRConfig {
|
||||
|
||||
private WindowConfig window = new WindowConfig();
|
||||
|
||||
private FiltersConfig filters = new FiltersConfig();
|
||||
|
||||
private AutoBoneConfig autobone = new AutoBoneConfig();
|
||||
|
||||
private KeybindingsConfig keybindings = new KeybindingsConfig();
|
||||
|
||||
private SkeletonConfig skeleton = new SkeletonConfig();
|
||||
|
||||
@JsonDeserialize(using = TrackerConfigMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
private Map<String, TrackerConfig> trackers = new HashMap<>();
|
||||
|
||||
@JsonDeserialize(using = BridgeConfigMapDeserializer.class)
|
||||
@JsonSerialize(keyUsing = StdKeySerializers.StringKeySerializer.class)
|
||||
private Map<String, BridgeConfig> bridges = new HashMap<>();
|
||||
|
||||
private OverlayConfig overlay = new OverlayConfig();
|
||||
|
||||
public WindowConfig getWindow() {
|
||||
return window;
|
||||
}
|
||||
|
||||
public FiltersConfig getFilters() {
|
||||
return filters;
|
||||
}
|
||||
|
||||
public AutoBoneConfig getAutoBone() {
|
||||
return autobone;
|
||||
}
|
||||
|
||||
public KeybindingsConfig getKeybindings() {
|
||||
return keybindings;
|
||||
}
|
||||
|
||||
public Map<String, TrackerConfig> getTrackers() {
|
||||
return trackers;
|
||||
}
|
||||
|
||||
public Map<String, BridgeConfig> getBridges() {
|
||||
return bridges;
|
||||
}
|
||||
|
||||
public SkeletonConfig getSkeleton() {
|
||||
return skeleton;
|
||||
}
|
||||
|
||||
public OverlayConfig getOverlay() {
|
||||
return overlay;
|
||||
}
|
||||
|
||||
public TrackerConfig getTracker(Tracker tracker) {
|
||||
TrackerConfig config = trackers.get(tracker.getName());
|
||||
if (config == null) {
|
||||
config = new TrackerConfig(tracker);
|
||||
trackers.put(tracker.getName(), config);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
public void readTrackerConfig(Tracker tracker) {
|
||||
TrackerConfig config = getTracker(tracker);
|
||||
tracker.readConfig(config);
|
||||
}
|
||||
|
||||
public void writeTrackerConfig(Tracker tracker) {
|
||||
TrackerConfig tc = getTracker(tracker);
|
||||
tracker.writeConfig(tc);
|
||||
}
|
||||
|
||||
public BridgeConfig getBrige(String bridgeKey) {
|
||||
BridgeConfig config = bridges.get(bridgeKey);
|
||||
if (config == null) {
|
||||
config = new BridgeConfig();
|
||||
bridges.put(bridgeKey, config);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package dev.slimevr.config;
|
||||
|
||||
|
||||
public class WindowConfig {
|
||||
|
||||
public static final float INITAL_ZOOM = 1.5f;
|
||||
|
||||
private float zoom = INITAL_ZOOM;
|
||||
|
||||
private int width = 800;
|
||||
|
||||
private int height = 800;
|
||||
|
||||
private int posx = -1;
|
||||
private int posy = -1;
|
||||
|
||||
public WindowConfig() {
|
||||
}
|
||||
|
||||
public float getZoom() {
|
||||
return zoom;
|
||||
}
|
||||
|
||||
public void setZoom(float zoom) {
|
||||
this.zoom = zoom;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public int getPosx() {
|
||||
return posx;
|
||||
}
|
||||
|
||||
public void setPosx(int posx) {
|
||||
this.posx = posx;
|
||||
}
|
||||
|
||||
public int getPosy() {
|
||||
return posy;
|
||||
}
|
||||
|
||||
public void setPosy(int posy) {
|
||||
this.posy = posy;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
/**
|
||||
* This class allows the use of the utility super class MapDeserializer that
|
||||
* takes the Value of a map as its Generic parameter. It is so you can use that
|
||||
* class in a @JsonDeserialize annotation on the Map field inside the config
|
||||
* instance
|
||||
*
|
||||
* @see dev.slimevr.config.VRConfig
|
||||
*/
|
||||
public class BooleanMapDeserializer extends MapDeserializer<Boolean> {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
import dev.slimevr.config.BridgeConfig;
|
||||
|
||||
|
||||
/**
|
||||
* This class allows the use of the utility super class MapDeserializer that
|
||||
* takes the Value of a map as its Generic parameter. It is so you can use that
|
||||
* class in a @JsonDeserialize annotation on the Map field inside the config
|
||||
* instance
|
||||
*
|
||||
* @see dev.slimevr.config.VRConfig
|
||||
*/
|
||||
public class BridgeConfigMapDeserializer extends MapDeserializer<BridgeConfig> {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
/**
|
||||
* This class allows the use of the utility super class MapDeserializer that
|
||||
* takes the Value of a map as its Generic parameter. It is so you can use that
|
||||
* class in a @JsonDeserialize annotation on the Map field inside the config
|
||||
* instance
|
||||
*
|
||||
* @see dev.slimevr.config.VRConfig
|
||||
*/
|
||||
public class FloatMapDeserializer extends MapDeserializer<Float> {
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.type.MapType;
|
||||
import com.fasterxml.jackson.databind.type.TypeFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.util.HashMap;
|
||||
|
||||
|
||||
/**
|
||||
* This class is an utility class that allows to write Map serializers easily to
|
||||
* be used in the VRConfig (@see {@link dev.slimevr.config.VRConfig})
|
||||
*
|
||||
* @see BooleanMapDeserializer to see how it is used
|
||||
*/
|
||||
public class MapDeserializer<T> extends JsonDeserializer<HashMap<String, T>> {
|
||||
|
||||
public MapDeserializer() {
|
||||
super();
|
||||
}
|
||||
|
||||
private Class<T> getGenericTypeClass() {
|
||||
try {
|
||||
String className = ((ParameterizedType) getClass().getGenericSuperclass())
|
||||
.getActualTypeArguments()[0].getTypeName();
|
||||
Class<?> clazz = Class.forName(className);
|
||||
return (Class<T>) clazz;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(
|
||||
"Class is not parametrized with generic type!!! Please use extends <> "
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<String, T> deserialize(JsonParser p, DeserializationContext dc)
|
||||
throws IOException, JsonProcessingException {
|
||||
TypeFactory typeFactory = dc.getTypeFactory();
|
||||
MapType mapType = typeFactory
|
||||
.constructMapType(HashMap.class, String.class, getGenericTypeClass());
|
||||
HashMap<String, T> map = dc.readValue(p, mapType);
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
import com.fasterxml.jackson.core.JacksonException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class QuaternionDeserializer extends JsonDeserializer<Quaternion> {
|
||||
@Override
|
||||
public Quaternion deserialize(JsonParser p, DeserializationContext ctxt)
|
||||
throws IOException, JacksonException {
|
||||
JsonNode node = p.getCodec().readTree(p);
|
||||
|
||||
return new Quaternion(
|
||||
(float) node.get("x").asDouble(),
|
||||
(float) node.get("y").asDouble(),
|
||||
(float) node.get("z").asDouble(),
|
||||
(float) node.get("w").asDouble()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.jme3.math.Quaternion;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class QuaternionSerializer extends JsonSerializer<Quaternion> {
|
||||
|
||||
@Override
|
||||
public void serialize(Quaternion value, JsonGenerator gen, SerializerProvider serializers)
|
||||
throws IOException {
|
||||
gen.writeStartObject();
|
||||
gen.writeNumberField("x", value.getX());
|
||||
gen.writeNumberField("y", value.getY());
|
||||
gen.writeNumberField("z", value.getZ());
|
||||
gen.writeNumberField("w", value.getW());
|
||||
gen.writeEndObject();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.slimevr.config.serializers;
|
||||
|
||||
import dev.slimevr.config.TrackerConfig;
|
||||
|
||||
|
||||
/**
|
||||
* This class allows the use of the utility super class MapDeserializer that
|
||||
* takes the Value of a map as its Generic parameter. It is so you can use that
|
||||
* class in a @JsonDeserialize annotation on the Map field inside the config
|
||||
* instance
|
||||
*
|
||||
* @see dev.slimevr.config.VRConfig
|
||||
*/
|
||||
public class TrackerConfigMapDeserializer extends MapDeserializer<TrackerConfig> {
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package dev.slimevr.filtering;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* If you use this code, please consider notifying isak at du-preez dot com with
|
||||
* a brief description of your application.
|
||||
* <p>
|
||||
* This is free and unencumbered software released into the public domain.
|
||||
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
|
||||
* this software, either in source code form or as a compiled binary, for any
|
||||
* purpose, commercial or non-commercial, and by any means.
|
||||
*/
|
||||
|
||||
public class CircularArrayList<E> extends AbstractList<E> implements RandomAccess {
|
||||
|
||||
private final int n; // buffer length
|
||||
private final List<E> buf; // a List implementing RandomAccess
|
||||
private int head = 0;
|
||||
private int tail = 0;
|
||||
|
||||
public CircularArrayList(int capacity) {
|
||||
n = capacity + 1;
|
||||
buf = new ArrayList<>(Collections.nCopies(n, null));
|
||||
}
|
||||
|
||||
public int capacity() {
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
private int wrapIndex(int i) {
|
||||
int m = i % n;
|
||||
if (m < 0) { // java modulus can be negative
|
||||
m += n;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// This method is O(n) but will never be called if the
|
||||
// CircularArrayList is used in its typical/intended role.
|
||||
private void shiftBlock(int startIndex, int endIndex) {
|
||||
assert (endIndex > startIndex);
|
||||
for (int i = endIndex - 1; i >= startIndex; i--) {
|
||||
set(i + 1, get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return tail - head + (tail < head ? n : 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E get(int i) {
|
||||
if (i < 0 || i >= size()) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return buf.get(wrapIndex(head + i));
|
||||
}
|
||||
|
||||
public E getLatest() {
|
||||
return buf.get(wrapIndex(head + size() - 1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public E set(int i, E e) {
|
||||
if (i < 0 || i >= size()) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return buf.set(wrapIndex(head + i), e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int i, E e) {
|
||||
int s = size();
|
||||
if (s == n - 1) {
|
||||
throw new IllegalStateException(
|
||||
"CircularArrayList is filled to capacity. "
|
||||
+ "(You may want to remove from front"
|
||||
+ " before adding more to back.)"
|
||||
);
|
||||
}
|
||||
if (i < 0 || i > s) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
tail = wrapIndex(tail + 1);
|
||||
if (i < s) {
|
||||
shiftBlock(i, s);
|
||||
}
|
||||
set(i, e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E remove(int i) {
|
||||
int s = size();
|
||||
if (i < 0 || i >= s) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
E e = get(i);
|
||||
if (i > 0) {
|
||||
shiftBlock(0, i);
|
||||
}
|
||||
head = wrapIndex(head + 1);
|
||||
return e;
|
||||
}
|
||||
|
||||
public E removeLast() {
|
||||
int s = size();
|
||||
if (0 == s) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
E e = get(0);
|
||||
head = wrapIndex(head + 1);
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package dev.slimevr.filtering;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.system.NanoTimer;
|
||||
import dev.slimevr.Main;
|
||||
|
||||
|
||||
public class QuaternionMovingAverage {
|
||||
|
||||
private final float smoothFactor;
|
||||
private final float predictFactor;
|
||||
private final CircularArrayList<Quaternion> rotBuffer;
|
||||
private final Quaternion quatBuf = new Quaternion();
|
||||
private final Quaternion latestQuaternion;
|
||||
private final Quaternion smoothingQuaternion;
|
||||
private final Quaternion filteredQuaternion;
|
||||
private final boolean smooths;
|
||||
private final boolean predicts;
|
||||
private final NanoTimer fpsTimer;
|
||||
private int smoothingCounter;
|
||||
|
||||
// influences the range of smoothFactor.
|
||||
private static final float SMOOTH_MULTIPLIER = 42f;
|
||||
private static final float SMOOTH_MIN = 20f;
|
||||
|
||||
// influences the range of predictFactor
|
||||
private static final float PREDICT_MULTIPLIER = 14f;
|
||||
private static final float PREDICT_MIN = 10f;
|
||||
|
||||
// how many past rotations are used for prediction.
|
||||
private static final int PREDICT_BUFFER = 6;
|
||||
|
||||
|
||||
public QuaternionMovingAverage(
|
||||
TrackerFilters type,
|
||||
float amount,
|
||||
Quaternion initialRotation
|
||||
) {
|
||||
fpsTimer = Main.vrServer.getFpsTimer();
|
||||
|
||||
// amount should range from 0 to 1.
|
||||
// GUI should clamp it from 0.01 (1%) or 0.1 (10%)
|
||||
// to 1 (100%).
|
||||
amount = Math.max(amount, 0);
|
||||
|
||||
if (type == TrackerFilters.SMOOTHING) {
|
||||
smooths = true;
|
||||
// lower smoothFactor = more smoothing
|
||||
smoothFactor = SMOOTH_MULTIPLIER * (1 - amount) + SMOOTH_MIN;
|
||||
} else {
|
||||
smooths = false;
|
||||
smoothFactor = 0f;
|
||||
}
|
||||
|
||||
if (type == TrackerFilters.PREDICTION) {
|
||||
predicts = true;
|
||||
// higher predictFactor = more prediction
|
||||
predictFactor = (PREDICT_MULTIPLIER * amount) + PREDICT_MIN;
|
||||
rotBuffer = new CircularArrayList<>(PREDICT_BUFFER);
|
||||
} else {
|
||||
predicts = false;
|
||||
predictFactor = 0;
|
||||
rotBuffer = null;
|
||||
}
|
||||
|
||||
filteredQuaternion = new Quaternion(initialRotation);
|
||||
latestQuaternion = new Quaternion(initialRotation);
|
||||
smoothingQuaternion = new Quaternion(initialRotation);
|
||||
}
|
||||
|
||||
// Runs at up to 1000hz. We use a timer to make it framerate-independent
|
||||
// since it runs between 850hz to 900hz in practice.
|
||||
synchronized public void update() {
|
||||
if (predicts) {
|
||||
if (rotBuffer.size() > 0) {
|
||||
quatBuf.set(latestQuaternion);
|
||||
|
||||
// Applies the past rotations to the current rotation
|
||||
rotBuffer.forEach(quatBuf::multLocal);
|
||||
|
||||
// Slerps the target rotation to that predicted rotation by
|
||||
// a certain factor.
|
||||
filteredQuaternion
|
||||
.slerpLocal(quatBuf, predictFactor * fpsTimer.getTimePerFrame());
|
||||
}
|
||||
}
|
||||
|
||||
if (smooths) {
|
||||
// Calculate the slerp factor and limit it to 1 max
|
||||
smoothingCounter++;
|
||||
float amt = Math.min(smoothFactor * fpsTimer.getTimePerFrame() * smoothingCounter, 1);
|
||||
|
||||
// Smooth towards the target rotation
|
||||
filteredQuaternion
|
||||
.slerp(
|
||||
smoothingQuaternion,
|
||||
latestQuaternion,
|
||||
amt
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized public void addQuaternion(Quaternion q) {
|
||||
if (predicts) {
|
||||
if (rotBuffer.size() == rotBuffer.capacity()) {
|
||||
rotBuffer.removeLast();
|
||||
}
|
||||
|
||||
// Gets and stores the rotation between the last 2 quaternions
|
||||
quatBuf.set(latestQuaternion);
|
||||
quatBuf.inverseLocal();
|
||||
rotBuffer.add(quatBuf.mult(q));
|
||||
}
|
||||
|
||||
if (smooths) {
|
||||
smoothingCounter = 0;
|
||||
smoothingQuaternion.set(filteredQuaternion);
|
||||
}
|
||||
|
||||
latestQuaternion.set(q);
|
||||
}
|
||||
|
||||
public Quaternion getFilteredQuaternion() {
|
||||
return filteredQuaternion.clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dev.slimevr.filtering;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public enum TrackerFilters {
|
||||
|
||||
NONE(0, "none"),
|
||||
SMOOTHING(1, "smoothing"),
|
||||
PREDICTION(2, "prediction");
|
||||
|
||||
private static final Map<String, TrackerFilters> byConfigkey = new HashMap<>();
|
||||
|
||||
static {
|
||||
for (TrackerFilters configVal : values()) {
|
||||
byConfigkey.put(configVal.configKey.toLowerCase(), configVal);
|
||||
}
|
||||
}
|
||||
|
||||
public static final TrackerFilters[] values = values();
|
||||
public final int id;
|
||||
public final String configKey;
|
||||
|
||||
TrackerFilters(int id, String configKey) {
|
||||
this.id = id;
|
||||
this.configKey = configKey;
|
||||
}
|
||||
|
||||
public static TrackerFilters fromId(int id) {
|
||||
for (TrackerFilters filter : values) {
|
||||
if (filter.id == id)
|
||||
return filter;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static TrackerFilters getByConfigkey(String configKey) {
|
||||
return configKey == null ? null : byConfigkey.get(configKey.toLowerCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import java.awt.event.ComponentEvent;
|
||||
import java.awt.event.ComponentListener;
|
||||
|
||||
|
||||
public abstract class AbstractComponentListener implements ComponentListener {
|
||||
|
||||
@Override
|
||||
public void componentResized(ComponentEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void componentMoved(ComponentEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void componentShown(ComponentEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void componentHidden(ComponentEvent e) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.awt.event.WindowListener;
|
||||
|
||||
|
||||
public abstract class AbstractWindowListener implements WindowListener {
|
||||
|
||||
@Override
|
||||
public void windowOpened(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowClosing(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowClosed(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowIconified(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowDeiconified(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowActivated(WindowEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowDeactivated(WindowEvent e) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
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.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.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
|
||||
|
||||
public class AutoBoneWindow extends JFrame implements AutoBoneListener {
|
||||
|
||||
private EJBox pane;
|
||||
|
||||
private final transient VRServer server;
|
||||
private final transient SkeletonConfigGUI skeletonConfig;
|
||||
|
||||
private JButton saveRecordingButton;
|
||||
private JButton applyButton;
|
||||
|
||||
private JLabel processLabel;
|
||||
private JLabel lengthsLabel;
|
||||
|
||||
public AutoBoneWindow(VRServer server, SkeletonConfigGUI skeletonConfig) {
|
||||
super("Skeleton Auto-Configuration");
|
||||
|
||||
this.server = server;
|
||||
this.skeletonConfig = skeletonConfig;
|
||||
|
||||
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
|
||||
add(
|
||||
new JScrollPane(
|
||||
pane = new EJBox(BoxLayout.PAGE_AXIS),
|
||||
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
|
||||
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
|
||||
)
|
||||
);
|
||||
|
||||
server.getAutoBoneHandler().addListener(this);
|
||||
|
||||
build();
|
||||
}
|
||||
|
||||
|
||||
@AWTThread
|
||||
private void build() {
|
||||
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(new JButton("Start Recording") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
server.getAutoBoneHandler().startRecording();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
add(saveRecordingButton = new JButton("Save Recording") {
|
||||
{
|
||||
setEnabled(false);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
server.getAutoBoneHandler().saveRecording();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
add(new JButton("Auto-Adjust") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
server.getAutoBoneHandler().processRecording();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
add(applyButton = new JButton("Apply Values") {
|
||||
{
|
||||
setEnabled(false);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
server.getAutoBoneHandler().applyValues();
|
||||
// Update GUI values after applying
|
||||
skeletonConfig.refreshAll();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(processLabel = new JLabel("Processing has not been started..."));
|
||||
}
|
||||
});
|
||||
|
||||
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(lengthsLabel = new JLabel("No config changes"));
|
||||
}
|
||||
});
|
||||
|
||||
// Pack and display
|
||||
pack();
|
||||
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 (SD %.4f)",
|
||||
epoch.epoch,
|
||||
epoch.totalEpochs,
|
||||
(epoch.epoch / (double) epoch.totalEpochs) * 100.0,
|
||||
epoch.epochError.getMean(),
|
||||
epoch.epochError.getStandardDeviation()
|
||||
)
|
||||
);
|
||||
lengthsLabel.setText(server.getAutoBoneHandler().getLengthsString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAutoBoneEnd(EnumMap<SkeletonConfigOffsets, Float> configValues) {
|
||||
applyButton.setEnabled(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import dev.slimevr.gui.swing.EJBox;
|
||||
import dev.slimevr.vr.trackers.CalibratingTracker;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import io.eiren.util.ann.AWTThread;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import javax.swing.event.MouseInputAdapter;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseEvent;
|
||||
|
||||
|
||||
public class CalibrationWindow extends JFrame {
|
||||
|
||||
public final Tracker tracker;
|
||||
private JTextArea currentCalibration;
|
||||
private JTextArea newCalibration;
|
||||
private JButton calibrateButton;
|
||||
|
||||
public CalibrationWindow(Tracker t) {
|
||||
super(t.getName() + " calibration");
|
||||
this.tracker = t;
|
||||
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
|
||||
|
||||
build();
|
||||
}
|
||||
|
||||
public void currentCalibrationReceived(String str) {
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
currentCalibration.setText(str);
|
||||
pack();
|
||||
});
|
||||
}
|
||||
|
||||
public void newCalibrationReceived(String str) {
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
calibrateButton.setText("Calibrate");
|
||||
newCalibration.setText(str);
|
||||
pack();
|
||||
});
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void build() {
|
||||
Container pane = getContentPane();
|
||||
|
||||
pane.add(calibrateButton = new JButton("Calibrate") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
calibrateButton.setText("Calibrating...");
|
||||
((CalibratingTracker) tracker)
|
||||
.startCalibration(CalibrationWindow.this::newCalibrationReceived);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(new JLabel("Current calibration"));
|
||||
add(currentCalibration = new JTextArea(10, 25));
|
||||
|
||||
((CalibratingTracker) tracker)
|
||||
.requestCalibrationData(CalibrationWindow.this::currentCalibrationReceived);
|
||||
}
|
||||
});
|
||||
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(new JLabel("New calibration"));
|
||||
add(newCalibration = new JTextArea(10, 25));
|
||||
}
|
||||
});
|
||||
|
||||
// Pack and display
|
||||
pack();
|
||||
setLocationRelativeTo(null);
|
||||
setVisible(true);
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
toFront();
|
||||
repaint();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import com.melloware.jintellitype.HotkeyListener;
|
||||
import com.melloware.jintellitype.JIntellitype;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.config.KeybindingsConfig;
|
||||
import io.eiren.util.OperatingSystem;
|
||||
import io.eiren.util.ann.AWTThread;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
|
||||
public class Keybinding implements HotkeyListener {
|
||||
private static final int RESET = 1;
|
||||
private static final int QUICK_RESET = 2;
|
||||
public final VRServer server;
|
||||
|
||||
|
||||
public final KeybindingsConfig config;
|
||||
|
||||
@AWTThread
|
||||
public Keybinding(VRServer server) {
|
||||
this.server = server;
|
||||
|
||||
this.config = server.getConfigManager().getVrConfig().getKeybindings();
|
||||
|
||||
if (OperatingSystem.getCurrentPlatform() != OperatingSystem.WINDOWS) {
|
||||
LogManager
|
||||
.info(
|
||||
"[Keybinding] Currently only supported on Windows. Keybindings will be disabled."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (JIntellitype.getInstance() instanceof JIntellitype) {
|
||||
JIntellitype.getInstance().addHotKeyListener(this);
|
||||
|
||||
String resetBinding = this.config.getResetBinding();
|
||||
JIntellitype.getInstance().registerHotKey(RESET, resetBinding);
|
||||
LogManager.info("[Keybinding] Bound reset to " + resetBinding);
|
||||
|
||||
String quickResetBinding = this.config.getQuickResetBinding();
|
||||
JIntellitype.getInstance().registerHotKey(QUICK_RESET, quickResetBinding);
|
||||
LogManager.info("[Keybinding] Bound quick reset to " + quickResetBinding);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
LogManager
|
||||
.info(
|
||||
"[Keybinding] JIntellitype initialization failed. Keybindings will be disabled. Try restarting your computer."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
@Override
|
||||
public void onHotKey(int identifier) {
|
||||
switch (identifier) {
|
||||
case RESET -> {
|
||||
LogManager.info("[Keybinding] Reset pressed");
|
||||
server.resetTrackers();
|
||||
}
|
||||
case QUICK_RESET -> {
|
||||
LogManager.info("[Keybinding] Quick reset pressed");
|
||||
server.resetTrackersYaw();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import java.awt.*;
|
||||
import java.text.AttributedCharacterIterator.Attribute;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class ScalableFont extends Font {
|
||||
|
||||
protected float scale = 1.0f;
|
||||
|
||||
protected int initSize;
|
||||
protected float initPointSize;
|
||||
|
||||
public ScalableFont(Map<? extends Attribute, ?> attributes) {
|
||||
super(attributes);
|
||||
|
||||
this.initSize = this.size;
|
||||
this.initPointSize = this.pointSize;
|
||||
}
|
||||
|
||||
public ScalableFont(Font font) {
|
||||
super(font);
|
||||
|
||||
if (font instanceof ScalableFont sourceFont) {
|
||||
|
||||
this.initSize = sourceFont.getInitSize();
|
||||
this.initPointSize = sourceFont.getInitSize2D();
|
||||
|
||||
this.size = this.initSize;
|
||||
this.pointSize = this.initPointSize;
|
||||
} else {
|
||||
this.initSize = this.size;
|
||||
this.initPointSize = this.pointSize;
|
||||
}
|
||||
}
|
||||
|
||||
public ScalableFont(Font font, float scale) {
|
||||
super(font);
|
||||
|
||||
if (font instanceof ScalableFont sourceFont) {
|
||||
|
||||
this.initSize = sourceFont.getInitSize();
|
||||
this.initPointSize = sourceFont.getInitSize2D();
|
||||
} else {
|
||||
this.initSize = this.size;
|
||||
this.initPointSize = this.pointSize;
|
||||
}
|
||||
|
||||
setScale(scale);
|
||||
}
|
||||
|
||||
public ScalableFont(String name, int style, int size) {
|
||||
super(name, style, size);
|
||||
|
||||
this.initSize = this.size;
|
||||
this.initPointSize = this.pointSize;
|
||||
}
|
||||
|
||||
public ScalableFont(String name, int style, int size, float scale) {
|
||||
super(name, style, size);
|
||||
|
||||
this.initSize = this.size;
|
||||
this.initPointSize = this.pointSize;
|
||||
|
||||
setScale(scale);
|
||||
}
|
||||
|
||||
public int getInitSize() {
|
||||
return initSize;
|
||||
}
|
||||
|
||||
public float getInitSize2D() {
|
||||
return initPointSize;
|
||||
}
|
||||
|
||||
public float getScale() {
|
||||
return scale;
|
||||
}
|
||||
|
||||
private void setScale(float scale) {
|
||||
this.scale = scale;
|
||||
|
||||
float newPointSize = initPointSize * scale;
|
||||
|
||||
this.size = (int) (newPointSize + 0.5);
|
||||
this.pointSize = newPointSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.gui.swing.ButtonTimer;
|
||||
import dev.slimevr.gui.swing.EJBagNoStretch;
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.MouseInputAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class SkeletonConfigGUI extends EJBagNoStretch {
|
||||
|
||||
private final VRServer server;
|
||||
private final VRServerGUI gui;
|
||||
private final AutoBoneWindow autoBone;
|
||||
private final Map<SkeletonConfigOffsets, SkeletonLabel> labels = new HashMap<>();
|
||||
private JCheckBox precisionCb;
|
||||
|
||||
public SkeletonConfigGUI(VRServer server, VRServerGUI gui) {
|
||||
super(false, true);
|
||||
this.server = server;
|
||||
this.gui = gui;
|
||||
this.autoBone = new AutoBoneWindow(server, this);
|
||||
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
server.humanPoseProcessor.addSkeletonUpdatedCallback(this::skeletonUpdated);
|
||||
skeletonUpdated(null);
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void skeletonUpdated(Skeleton newSkeleton) {
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
removeAll();
|
||||
|
||||
int row = 0;
|
||||
|
||||
add(new TimedResetButton("Reset All"), s(c(1, row, 2), 3, 1));
|
||||
add(new JButton("Auto") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
autoBone.setVisible(true);
|
||||
autoBone.toFront();
|
||||
}
|
||||
});
|
||||
}
|
||||
}, s(c(4, row, 2), 3, 1));
|
||||
|
||||
add(precisionCb = new JCheckBox("Precision adjust"), c(0, row, 2));
|
||||
precisionCb.setSelected(false);
|
||||
|
||||
row++;
|
||||
|
||||
for (SkeletonConfigOffsets config : SkeletonConfigOffsets.values) {
|
||||
add(new JLabel(config.label), c(0, row, 2));
|
||||
add(new AdjButton("+", config, false), c(1, row, 2));
|
||||
add(new SkeletonLabel(config), c(2, row, 2));
|
||||
add(new AdjButton("-", config, true), c(3, row, 2));
|
||||
|
||||
// Only use a timer on configs that need time to get into
|
||||
// position for
|
||||
switch (config) {
|
||||
case TORSO, LEGS_LENGTH -> add(
|
||||
new TimedResetButton("Reset", config),
|
||||
c(4, row, 2)
|
||||
);
|
||||
default -> add(new ResetButton("Reset", config), c(4, row, 2));
|
||||
}
|
||||
|
||||
row++;
|
||||
}
|
||||
|
||||
gui.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
float proportionsIncrement(Boolean negative) {
|
||||
float increment = 0.01f;
|
||||
if (negative)
|
||||
increment = -0.01f;
|
||||
if (precisionCb.isSelected())
|
||||
increment /= 2f;
|
||||
return increment;
|
||||
}
|
||||
|
||||
String getBoneLengthString(SkeletonConfigOffsets joint) { // Rounded to
|
||||
// the
|
||||
// nearest 0.5
|
||||
return (StringUtils
|
||||
.prettyNumber(
|
||||
Math.round(server.humanPoseProcessor.getSkeletonConfig(joint) * 200) / 2.0f,
|
||||
1
|
||||
));
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void refreshAll() {
|
||||
java.awt.EventQueue
|
||||
.invokeLater(
|
||||
() -> labels.forEach((joint, label) -> label.setText(getBoneLengthString(joint)))
|
||||
);
|
||||
}
|
||||
|
||||
private void change(SkeletonConfigOffsets joint, float diff) {
|
||||
// Update config value
|
||||
float current = server.humanPoseProcessor.getSkeletonConfig(joint);
|
||||
server.humanPoseProcessor.setSkeletonConfig(joint, current + diff);
|
||||
server.humanPoseProcessor.getSkeletonConfig().save();
|
||||
server.getConfigManager().saveConfig();
|
||||
|
||||
// Update GUI
|
||||
labels.get(joint).setText(getBoneLengthString(joint));
|
||||
}
|
||||
|
||||
private void reset(SkeletonConfigOffsets joint) {
|
||||
// Update config value
|
||||
server.humanPoseProcessor.resetSkeletonConfig(joint);
|
||||
server.humanPoseProcessor.getSkeletonConfig().save();
|
||||
server.getConfigManager().saveConfig();
|
||||
|
||||
// Update GUI
|
||||
labels.get(joint).setText(getBoneLengthString(joint));
|
||||
}
|
||||
|
||||
private void resetAll() {
|
||||
// Update config value
|
||||
server.humanPoseProcessor.resetAllSkeletonConfigs();
|
||||
server.humanPoseProcessor.getSkeletonConfig().save();
|
||||
server.getConfigManager().saveConfig();
|
||||
|
||||
// Update GUI
|
||||
refreshAll();
|
||||
}
|
||||
|
||||
private class SkeletonLabel extends JLabel {
|
||||
|
||||
public SkeletonLabel(SkeletonConfigOffsets joint) {
|
||||
super(getBoneLengthString(joint));
|
||||
labels.put(joint, this);
|
||||
}
|
||||
}
|
||||
|
||||
private class AdjButton extends JButton {
|
||||
|
||||
public AdjButton(String text, SkeletonConfigOffsets joint, boolean negative) {
|
||||
super(text);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
change(joint, proportionsIncrement(negative));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private class ResetButton extends JButton {
|
||||
|
||||
public ResetButton(String text, SkeletonConfigOffsets joint) {
|
||||
super(text);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
reset(joint);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private class TimedResetButton extends JButton {
|
||||
|
||||
public TimedResetButton(String text, SkeletonConfigOffsets joint) {
|
||||
super(text);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
ButtonTimer.runTimer(TimedResetButton.this, 3, text, () -> reset(joint));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public TimedResetButton(String text) {
|
||||
super(text);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
ButtonTimer
|
||||
.runTimer(TimedResetButton.this, 3, text, SkeletonConfigGUI.this::resetAll);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.gui.swing.EJBagNoStretch;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.processor.TransformNode;
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
import io.eiren.util.collections.FastList;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class SkeletonList extends EJBagNoStretch {
|
||||
|
||||
private static final long UPDATE_DELAY = 50;
|
||||
private final VRServerGUI gui;
|
||||
private final List<NodeStatus> nodes = new FastList<>();
|
||||
Quaternion q = new Quaternion();
|
||||
Vector3f v = new Vector3f();
|
||||
float[] angles = new float[3];
|
||||
private long lastUpdate = 0;
|
||||
|
||||
public SkeletonList(VRServer server, VRServerGUI gui) {
|
||||
super(false, true);
|
||||
this.gui = gui;
|
||||
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
server.addSkeletonUpdatedCallback(this::skeletonUpdated);
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void skeletonUpdated(Skeleton newSkeleton) {
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
removeAll();
|
||||
nodes.clear();
|
||||
|
||||
add(new JLabel("Joint"), c(0, 0, 2));
|
||||
add(new JLabel("X"), c(1, 0, 2));
|
||||
add(new JLabel("Y"), c(2, 0, 2));
|
||||
add(new JLabel("Z"), c(3, 0, 2));
|
||||
add(new JLabel("Pitch"), c(4, 0, 2));
|
||||
add(new JLabel("Yaw"), c(5, 0, 2));
|
||||
add(new JLabel("Roll"), c(6, 0, 2));
|
||||
|
||||
TransformNode[] allNodes = newSkeleton.getAllNodes();
|
||||
|
||||
for (int i = 0; i < allNodes.length; i++) {
|
||||
nodes.add(new NodeStatus(allNodes[i], i + 1));
|
||||
}
|
||||
|
||||
gui.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public void updateBones() {
|
||||
if (lastUpdate + UPDATE_DELAY > System.currentTimeMillis())
|
||||
return;
|
||||
lastUpdate = System.currentTimeMillis();
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
for (NodeStatus node : nodes) {
|
||||
node.update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private class NodeStatus {
|
||||
|
||||
TransformNode n;
|
||||
JLabel x;
|
||||
JLabel y;
|
||||
JLabel z;
|
||||
JLabel a1;
|
||||
JLabel a2;
|
||||
JLabel a3;
|
||||
|
||||
public NodeStatus(TransformNode node, int n) {
|
||||
this.n = node;
|
||||
add(new JLabel(node.getName()), c(0, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(x = new JLabel("0"), c(1, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(y = new JLabel("0"), c(2, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(z = new JLabel("0"), c(3, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(a1 = new JLabel("0"), c(4, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(a2 = new JLabel("0"), c(5, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(a3 = new JLabel("0"), c(6, n, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
}
|
||||
|
||||
public void update() {
|
||||
n.worldTransform.getTranslation(v);
|
||||
n.worldTransform.getRotation(q);
|
||||
q.toAngles(angles);
|
||||
|
||||
x.setText(StringUtils.prettyNumber(v.x, 2));
|
||||
y.setText(StringUtils.prettyNumber(v.y, 2));
|
||||
z.setText(StringUtils.prettyNumber(v.z, 2));
|
||||
a1.setText(StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0));
|
||||
a2.setText(StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0));
|
||||
a3.setText(StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.config.FiltersConfig;
|
||||
import dev.slimevr.filtering.TrackerFilters;
|
||||
import dev.slimevr.gui.swing.EJBagNoStretch;
|
||||
import io.eiren.util.StringUtils;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.MouseInputAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
|
||||
|
||||
public class TrackersFiltersGUI extends EJBagNoStretch {
|
||||
|
||||
private final VRServer server;
|
||||
private final JLabel amountLabel;
|
||||
TrackerFilters filterType;
|
||||
float filterAmount;
|
||||
FiltersConfig filtersConfig;
|
||||
|
||||
public TrackersFiltersGUI(VRServer server, VRServerGUI gui) {
|
||||
|
||||
super(false, true);
|
||||
this.server = server;
|
||||
filtersConfig = server
|
||||
.getConfigManager()
|
||||
.getVrConfig()
|
||||
.getFilters();
|
||||
|
||||
int row = 0;
|
||||
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
add(Box.createVerticalStrut(10));
|
||||
filterType = server.getConfigManager().getVrConfig().getFilters().enumGetType();
|
||||
|
||||
JComboBox<String> filterSelect;
|
||||
add(filterSelect = new JComboBox<>(), s(c(0, row, 2), 4, 1));
|
||||
|
||||
for (TrackerFilters f : TrackerFilters.values()) {
|
||||
filterSelect.addItem(f.name());
|
||||
}
|
||||
if (filterType != null) {
|
||||
filterSelect.setSelectedItem(filterType.toString());
|
||||
}
|
||||
|
||||
filterSelect.addActionListener((e) -> {
|
||||
filterType = TrackerFilters
|
||||
.getByConfigkey(filterSelect.getSelectedItem().toString());
|
||||
filtersConfig
|
||||
.enumSetType(filterType);
|
||||
filtersConfig
|
||||
.updateTrackersFilters();
|
||||
server.getConfigManager().saveConfig();
|
||||
});
|
||||
add(Box.createVerticalStrut(40));
|
||||
row++;
|
||||
|
||||
filterAmount = FastMath
|
||||
.clamp(
|
||||
server.getConfigManager().getVrConfig().getFilters().getAmount(),
|
||||
0.1f,
|
||||
1
|
||||
);
|
||||
|
||||
add(new JLabel("Amount"), c(0, row, 2));
|
||||
add(new AdjButton("+", false), c(1, row, 2));
|
||||
add(
|
||||
amountLabel = new JLabel(StringUtils.prettyNumber(filterAmount * 100f) + "%"),
|
||||
c(2, row, 2)
|
||||
);
|
||||
add(new AdjButton("-", true), c(3, row, 2));
|
||||
}
|
||||
|
||||
void adjustAmount(boolean neg) {
|
||||
if (neg) {
|
||||
filterAmount = FastMath.clamp(filterAmount - 0.1f, 0.1f, 1);
|
||||
} else {
|
||||
filterAmount = FastMath.clamp(filterAmount + 0.1f, 0.1f, 1);
|
||||
}
|
||||
amountLabel.setText((StringUtils.prettyNumber(filterAmount * 100f)) + "%");
|
||||
|
||||
filtersConfig
|
||||
.setAmount(filterAmount);
|
||||
filtersConfig
|
||||
.updateTrackersFilters();
|
||||
|
||||
server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
private class AdjButton extends JButton {
|
||||
|
||||
public AdjButton(String text, boolean neg) {
|
||||
super(text);
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
adjustAmount(neg);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.config.TrackerConfig;
|
||||
import dev.slimevr.gui.swing.EJBagNoStretch;
|
||||
import dev.slimevr.gui.swing.EJBoxNoStretch;
|
||||
import dev.slimevr.vr.trackers.*;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.ann.AWTThread;
|
||||
import io.eiren.util.ann.ThreadSafe;
|
||||
import io.eiren.util.collections.FastList;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
|
||||
public class TrackersList extends EJBoxNoStretch {
|
||||
|
||||
private static final long UPDATE_DELAY = 50;
|
||||
private final VRServer server;
|
||||
private final VRServerGUI gui;
|
||||
private final List<TrackerPanel> trackers = new FastList<>();
|
||||
Quaternion q = new Quaternion();
|
||||
Vector3f v = new Vector3f();
|
||||
float[] angles = new float[3];
|
||||
private long lastUpdate = 0;
|
||||
private boolean debug = false;
|
||||
|
||||
public TrackersList(VRServer server, VRServerGUI gui) {
|
||||
super(BoxLayout.PAGE_AXIS, false, true);
|
||||
this.server = server;
|
||||
this.gui = gui;
|
||||
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
|
||||
server.addNewTrackerConsumer(this::newTrackerAdded);
|
||||
}
|
||||
|
||||
private static int getTrackerSort(Tracker t) {
|
||||
Tracker tracker = t.get();
|
||||
if (tracker instanceof IMUTracker)
|
||||
return 0;
|
||||
if (tracker instanceof HMDTracker)
|
||||
return 100;
|
||||
if (tracker instanceof ComputedTracker)
|
||||
return 200;
|
||||
return 1000;
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
public void setDebug(boolean debug) {
|
||||
this.debug = debug;
|
||||
build();
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void build() {
|
||||
removeAll();
|
||||
|
||||
trackers.sort(Comparator.comparingInt(tr -> getTrackerSort(tr.t)));
|
||||
|
||||
Class<? extends Tracker> currentClass = null;
|
||||
|
||||
EJBoxNoStretch line = null;
|
||||
boolean first = true;
|
||||
|
||||
for (TrackerPanel tr : trackers) {
|
||||
Tracker t = tr.t.get();
|
||||
if (currentClass != t.getClass()) {
|
||||
currentClass = t.getClass();
|
||||
if (line != null)
|
||||
line.add(Box.createHorizontalGlue());
|
||||
line = null;
|
||||
line = new EJBoxNoStretch(BoxLayout.LINE_AXIS, false, true);
|
||||
line.add(Box.createHorizontalGlue());
|
||||
JLabel nameLabel;
|
||||
line.add(nameLabel = new JLabel(currentClass.getSimpleName()));
|
||||
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
|
||||
line.add(Box.createHorizontalGlue());
|
||||
add(line);
|
||||
line = null;
|
||||
}
|
||||
|
||||
if (line == null) {
|
||||
line = new EJBoxNoStretch(BoxLayout.LINE_AXIS, false, true);
|
||||
add(Box.createVerticalStrut(3));
|
||||
add(line);
|
||||
first = true;
|
||||
} else {
|
||||
line.add(Box.createHorizontalStrut(3));
|
||||
first = false;
|
||||
}
|
||||
tr.build();
|
||||
line.add(tr);
|
||||
if (!first)
|
||||
line = null;
|
||||
}
|
||||
validate();
|
||||
gui.refresh();
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void updateTrackers() {
|
||||
if (lastUpdate + UPDATE_DELAY > System.currentTimeMillis())
|
||||
return;
|
||||
lastUpdate = System.currentTimeMillis();
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
for (TrackerPanel tr : trackers) {
|
||||
tr.update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
public void newTrackerAdded(Tracker t) {
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
trackers.add(new TrackerPanel(t));
|
||||
build();
|
||||
});
|
||||
}
|
||||
|
||||
private class TrackerPanel extends EJBagNoStretch {
|
||||
|
||||
final Tracker t;
|
||||
JLabel position;
|
||||
JLabel rotation;
|
||||
JLabel status;
|
||||
JLabel url;
|
||||
JLabel tps;
|
||||
JLabel bat;
|
||||
JLabel ping;
|
||||
JLabel raw;
|
||||
JLabel rawMag;
|
||||
JLabel calibration;
|
||||
JLabel magAccuracy;
|
||||
JLabel adj;
|
||||
JLabel adjYaw;
|
||||
JLabel adjGyro;
|
||||
JLabel correction;
|
||||
JLabel signalStrength;
|
||||
JLabel rotQuat;
|
||||
JLabel rotAdj;
|
||||
JLabel temperature;
|
||||
JLabel accel;
|
||||
|
||||
@AWTThread
|
||||
public TrackerPanel(Tracker t) {
|
||||
super(false, true);
|
||||
|
||||
this.t = t;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@AWTThread
|
||||
public TrackerPanel build() {
|
||||
int row = 0;
|
||||
|
||||
Tracker tracker = t.get();
|
||||
removeAll();
|
||||
JLabel nameLabel;
|
||||
add(
|
||||
nameLabel = new JLabel(
|
||||
t.getCustomName() != null ? t.getCustomName() : t.getDisplayName()
|
||||
),
|
||||
s(c(0, row, 2, GridBagConstraints.FIRST_LINE_START), 4, 1)
|
||||
);
|
||||
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
|
||||
row++;
|
||||
|
||||
if (t.userEditable()) {
|
||||
TrackerConfig cfg = server.getConfigManager().getVrConfig().getTracker(t);
|
||||
JComboBox<String> desSelect;
|
||||
add(
|
||||
desSelect = new JComboBox<>(),
|
||||
s(c(0, row, 2, GridBagConstraints.FIRST_LINE_START), 2, 1)
|
||||
);
|
||||
desSelect.addItem("NONE");
|
||||
for (TrackerPosition p : TrackerPosition.values) {
|
||||
desSelect.addItem(p.name());
|
||||
}
|
||||
if (cfg.getDesignation() != null) {
|
||||
TrackerPosition
|
||||
.getByDesignation(cfg.getDesignation())
|
||||
.ifPresentOrElse(
|
||||
trackerPosition -> desSelect.setSelectedItem(trackerPosition.name()),
|
||||
() -> desSelect.setSelectedItem("NONE")
|
||||
);
|
||||
}
|
||||
desSelect.addActionListener(e -> {
|
||||
if (desSelect.getSelectedItem() == "NONE") {
|
||||
t.setBodyPosition(null);
|
||||
} else {
|
||||
TrackerPosition p = TrackerPosition
|
||||
.valueOf(String.valueOf(desSelect.getSelectedItem()));
|
||||
t.setBodyPosition(p);
|
||||
}
|
||||
server.trackerUpdated(t);
|
||||
});
|
||||
if (tracker instanceof IMUTracker imu) {
|
||||
JComboBox<String> mountSelect;
|
||||
add(
|
||||
mountSelect = new JComboBox<>(),
|
||||
s(c(2, row, 2, GridBagConstraints.FIRST_LINE_START), 2, 1)
|
||||
);
|
||||
for (TrackerMountingRotation p : TrackerMountingRotation.values) {
|
||||
mountSelect.addItem(p.name());
|
||||
}
|
||||
|
||||
TrackerMountingRotation selected = TrackerMountingRotation
|
||||
.fromQuaternion(imu.getMountingRotation());
|
||||
mountSelect
|
||||
.setSelectedItem(
|
||||
Objects
|
||||
.requireNonNullElse(selected, TrackerMountingRotation.BACK)
|
||||
.name()
|
||||
);
|
||||
mountSelect.addActionListener(e -> {
|
||||
TrackerMountingRotation tr = TrackerMountingRotation
|
||||
.valueOf(String.valueOf(mountSelect.getSelectedItem()));
|
||||
imu.setMountingRotation(tr.quaternion);
|
||||
server.trackerUpdated(t);
|
||||
});
|
||||
}
|
||||
row++;
|
||||
}
|
||||
|
||||
if (t.getDevice() != null && t.getDevice().getIpAddress() != null) {
|
||||
add(new JLabel("URL:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
url = new JLabel(""),
|
||||
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
row++;
|
||||
}
|
||||
|
||||
if (t.hasRotation())
|
||||
add(new JLabel("Rotation"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
if (t.hasPosition())
|
||||
add(new JLabel("Position"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(new JLabel("TPS"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
if (tracker instanceof TrackerWithWireless) {
|
||||
add(new JLabel("Ping"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(new JLabel("Signal"), c(4, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
}
|
||||
row++;
|
||||
if (t.hasRotation())
|
||||
add(
|
||||
rotation = new JLabel("0 0 0"),
|
||||
c(0, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
if (t.hasPosition())
|
||||
add(
|
||||
position = new JLabel("0 0 0"),
|
||||
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
if (tracker instanceof TrackerWithWireless) {
|
||||
add(ping = new JLabel(""), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
signalStrength = new JLabel(""),
|
||||
c(4, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
}
|
||||
if (tracker instanceof TrackerWithTPS) {
|
||||
add(tps = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
} else {
|
||||
add(new JLabel(""), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
}
|
||||
row++;
|
||||
add(new JLabel("Status:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
status = new JLabel(t.getStatus().toString().toLowerCase()),
|
||||
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
if (tracker instanceof TrackerWithBattery) {
|
||||
add(new JLabel("Battery:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(bat = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
}
|
||||
row++;
|
||||
add(new JLabel("Raw:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
raw = new JLabel("0 0 0"),
|
||||
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
|
||||
);
|
||||
|
||||
if (debug && tracker instanceof IMUTracker) {
|
||||
add(new JLabel("Quat:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(rotQuat = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
}
|
||||
row++;
|
||||
|
||||
if (debug && tracker instanceof IMUTracker) {
|
||||
add(new JLabel("Raw mag:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
rawMag = new JLabel("0 0 0"),
|
||||
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
|
||||
);
|
||||
add(new JLabel("Gyro fix:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
new JLabel(String.format("0x%8x", tracker.hashCode())),
|
||||
s(c(3, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
|
||||
);
|
||||
row++;
|
||||
add(new JLabel("Cal:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
calibration = new JLabel("0"),
|
||||
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
add(new JLabel("Mag acc:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
magAccuracy = new JLabel("0°"),
|
||||
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
row++;
|
||||
add(new JLabel("Correction:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
correction = new JLabel("0 0 0"),
|
||||
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
|
||||
);
|
||||
add(new JLabel("RotAdj:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(rotAdj = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
row++;
|
||||
|
||||
add(new JLabel("Accel:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(accel = new JLabel("0 0 0"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
row++;
|
||||
}
|
||||
|
||||
if (debug && t instanceof ReferenceAdjustedTracker) {
|
||||
add(new JLabel("Att fix:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(adj = new JLabel("0 0 0 0"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(new JLabel("Yaw Fix:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
adjYaw = new JLabel("0 0 0 0"),
|
||||
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
row++;
|
||||
add(new JLabel("Gyro Fix:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
adjGyro = new JLabel("0 0 0 0"),
|
||||
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
add(new JLabel("Temp:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
|
||||
add(
|
||||
temperature = new JLabel("?"),
|
||||
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
|
||||
);
|
||||
}
|
||||
|
||||
setBorder(BorderFactory.createLineBorder(new Color(0x663399), 2, false));
|
||||
TrackersList.this.add(this);
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@AWTThread
|
||||
public void update() {
|
||||
if (position == null && rotation == null)
|
||||
return;
|
||||
Tracker tracker = t.get();
|
||||
t.getRotation(q);
|
||||
t.getPosition(v);
|
||||
q.toAngles(angles);
|
||||
|
||||
if (position != null)
|
||||
position
|
||||
.setText(
|
||||
StringUtils.prettyNumber(v.x, 1)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(v.y, 1)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(v.z, 1)
|
||||
);
|
||||
if (rotation != null)
|
||||
rotation
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
status.setText(t.getStatus().toString().toLowerCase());
|
||||
if (t.getDevice() != null && t.getDevice().getIpAddress() != null)
|
||||
url.setText("udp:/" + t.getDevice().getIpAddress());
|
||||
|
||||
if (tracker instanceof TrackerWithTPS) {
|
||||
tps.setText(StringUtils.prettyNumber(((TrackerWithTPS) tracker).getTPS(), 1));
|
||||
}
|
||||
if (tracker instanceof TrackerWithBattery twb) {
|
||||
float level = twb.getBatteryLevel();
|
||||
float voltage = twb.getBatteryVoltage();
|
||||
if (level == 0.0f) {
|
||||
bat.setText(String.format("%sV", StringUtils.prettyNumber(voltage, 2)));
|
||||
} else if (voltage == 0.0f) {
|
||||
bat.setText(String.format("%d%%", Math.round(level)));
|
||||
} else {
|
||||
bat
|
||||
.setText(
|
||||
String
|
||||
.format(
|
||||
"%d%% (%sV)",
|
||||
Math.round(level),
|
||||
StringUtils.prettyNumber(voltage, 2)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (t instanceof ReferenceAdjustedTracker) {
|
||||
ReferenceAdjustedTracker<Tracker> rat = (ReferenceAdjustedTracker<Tracker>) t;
|
||||
if (adj != null) {
|
||||
rat.attachmentFix.toAngles(angles);
|
||||
adj
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (adjYaw != null) {
|
||||
rat.yawFix.toAngles(angles);
|
||||
adjYaw
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (adjGyro != null) {
|
||||
rat.gyroFix.toAngles(angles);
|
||||
adjGyro
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (tracker instanceof TrackerWithWireless) {
|
||||
ping.setText(String.valueOf(((TrackerWithWireless) tracker).getPing()));
|
||||
int signal = ((TrackerWithWireless) tracker).getSignalStrength();
|
||||
|
||||
if (signal == -1) {
|
||||
signalStrength.setText("N/A");
|
||||
} else {
|
||||
// -40 dBm is excellent, -95 dBm is very poor
|
||||
int percentage = (signal - -95) * (100 - 0) / (-40 - -95) + 0;
|
||||
percentage = Math.max(Math.min(percentage, 100), 0);
|
||||
signalStrength.setText(percentage + "% " + "(" + signal + " dBm" + ")");
|
||||
}
|
||||
}
|
||||
|
||||
tracker.getRotation(q);
|
||||
q.toAngles(angles);
|
||||
raw
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
if (tracker instanceof IMUTracker imu) {
|
||||
if (rawMag != null) {
|
||||
imu.rotMagQuaternion.toAngles(angles);
|
||||
rawMag
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (calibration != null)
|
||||
calibration.setText(imu.calibrationStatus + " / " + imu.magCalibrationStatus);
|
||||
if (magAccuracy != null)
|
||||
magAccuracy
|
||||
.setText(
|
||||
StringUtils
|
||||
.prettyNumber(imu.magnetometerAccuracy * FastMath.RAD_TO_DEG, 1)
|
||||
+ "°"
|
||||
);
|
||||
if (correction != null) {
|
||||
imu.getCorrection(q);
|
||||
q.toAngles(angles);
|
||||
correction
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (rotQuat != null) {
|
||||
imu.rotQuaternion.toAngles(angles);
|
||||
rotQuat
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (rotAdj != null) {
|
||||
imu.rotAdjust.toAngles(angles);
|
||||
rotAdj
|
||||
.setText(
|
||||
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
|
||||
);
|
||||
}
|
||||
if (temperature != null) {
|
||||
if (imu.temperature == 0.0f) {
|
||||
// Can't be exact 0, so no info received
|
||||
temperature.setText("?");
|
||||
} else {
|
||||
temperature.setText(StringUtils.prettyNumber(imu.temperature, 1) + "∘C");
|
||||
}
|
||||
}
|
||||
if (accel != null) {
|
||||
accel
|
||||
.setText(
|
||||
StringUtils.prettyNumber(imu.accelVector.x, 1)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(imu.accelVector.y, 1)
|
||||
+ " "
|
||||
+ StringUtils.prettyNumber(imu.accelVector.z, 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import dev.slimevr.Main;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.config.WindowConfig;
|
||||
import dev.slimevr.gui.swing.ButtonTimer;
|
||||
import dev.slimevr.gui.swing.EJBagNoStretch;
|
||||
import dev.slimevr.gui.swing.EJBox;
|
||||
import dev.slimevr.gui.swing.EJBoxNoStretch;
|
||||
import dev.slimevr.platform.windows.WindowsNamedPipeBridge;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigToggles;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
import io.eiren.util.MacOSX;
|
||||
import io.eiren.util.OperatingSystem;
|
||||
import io.eiren.util.StringUtils;
|
||||
import io.eiren.util.ann.AWTThread;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.EmptyBorder;
|
||||
import javax.swing.event.MouseInputAdapter;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.awt.event.ComponentEvent;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static javax.swing.BoxLayout.LINE_AXIS;
|
||||
import static javax.swing.BoxLayout.PAGE_AXIS;
|
||||
|
||||
|
||||
public class VRServerGUI extends JFrame {
|
||||
|
||||
public static final String TITLE = "SlimeVR Server (" + Main.VERSION + ")";
|
||||
|
||||
public final VRServer server;
|
||||
private final TrackersList trackersList;
|
||||
private final TrackersFiltersGUI trackersFiltersGUI;
|
||||
private final SkeletonList skeletonList;
|
||||
private final EJBox pane;
|
||||
private JButton resetButton;
|
||||
private JButton floorClipButton;
|
||||
private JButton skatingCorrectionButton;
|
||||
|
||||
private WindowConfig config;
|
||||
|
||||
@AWTThread
|
||||
public VRServerGUI(VRServer server) {
|
||||
super(TITLE);
|
||||
|
||||
this.config = server.getConfigManager().getVrConfig().getWindow();
|
||||
|
||||
try {
|
||||
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (OperatingSystem.getCurrentPlatform() == OperatingSystem.OSX)
|
||||
MacOSX.setTitle(TITLE);
|
||||
try {
|
||||
List<BufferedImage> images = new ArrayList<>(6);
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon16.png")));
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon32.png")));
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon48.png")));
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon64.png")));
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon128.png")));
|
||||
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon256.png")));
|
||||
setIconImages(images);
|
||||
if (OperatingSystem.getCurrentPlatform() == OperatingSystem.OSX) {
|
||||
MacOSX.setIcons(images);
|
||||
}
|
||||
} catch (IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
|
||||
this.server = server;
|
||||
|
||||
setDefaultFontSize(config.getZoom());
|
||||
// All components should be constructed to the current zoom level by
|
||||
// default
|
||||
|
||||
setDefaultCloseOperation(EXIT_ON_CLOSE);
|
||||
getContentPane().setLayout(new BoxLayout(getContentPane(), PAGE_AXIS));
|
||||
|
||||
this.trackersList = new TrackersList(server, this);
|
||||
trackersFiltersGUI = new TrackersFiltersGUI(server, this);
|
||||
this.skeletonList = new SkeletonList(server, this);
|
||||
|
||||
JScrollPane scrollPane = (JScrollPane) add(
|
||||
new JScrollPane(
|
||||
pane = new EJBox(PAGE_AXIS),
|
||||
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
|
||||
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
|
||||
)
|
||||
);
|
||||
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
|
||||
|
||||
GraphicsConfiguration gc = getGraphicsConfiguration();
|
||||
Rectangle screenBounds = gc.getBounds();
|
||||
setMinimumSize(new Dimension(100, 100));
|
||||
setSize(
|
||||
Math.min(config.getWidth(), screenBounds.width),
|
||||
Math.min(config.getHeight(), screenBounds.height)
|
||||
);
|
||||
|
||||
int posx = config.getPosx();
|
||||
if (posx == -1) {
|
||||
posx = screenBounds.x + (screenBounds.width - getSize().width) / 2;
|
||||
config.setPosx(posx);
|
||||
}
|
||||
|
||||
int posy = config.getPosy();
|
||||
if (posy == -1) {
|
||||
posy = (screenBounds.height - getSize().height) / 2;
|
||||
config.setPosy(posy);
|
||||
}
|
||||
|
||||
setLocation(posx, posy);
|
||||
|
||||
// Resize and close listeners to save position and size betwen launcher
|
||||
// starts
|
||||
addComponentListener(new AbstractComponentListener() {
|
||||
@Override
|
||||
public void componentResized(ComponentEvent e) {
|
||||
saveFrameInfo();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void componentMoved(ComponentEvent e) {
|
||||
saveFrameInfo();
|
||||
}
|
||||
});
|
||||
|
||||
build();
|
||||
}
|
||||
|
||||
private static void processNewZoom(float zoom, Component comp) {
|
||||
if (comp.isFontSet()) {
|
||||
Font newFont = new ScalableFont(comp.getFont(), zoom);
|
||||
comp.setFont(newFont);
|
||||
}
|
||||
if (comp instanceof Container cont) {
|
||||
for (Component child : cont.getComponents())
|
||||
processNewZoom(zoom, child);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setDefaultFontSize(float zoom) {
|
||||
java.util.Enumeration<Object> keys = UIManager.getDefaults().keys();
|
||||
while (keys.hasMoreElements()) {
|
||||
Object key = keys.nextElement();
|
||||
Object value = UIManager.get(key);
|
||||
if (value instanceof javax.swing.plaf.FontUIResource f) {
|
||||
javax.swing.plaf.FontUIResource f2 = new javax.swing.plaf.FontUIResource(
|
||||
f.deriveFont(f.getSize() * zoom)
|
||||
);
|
||||
UIManager.put(key, f2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void saveFrameInfo() {
|
||||
Rectangle b = getBounds();
|
||||
config.setWidth(b.width);
|
||||
config.setHeight(b.height);
|
||||
config.setPosx(b.x);
|
||||
config.setPosy(b.y);
|
||||
server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
// Pack and display
|
||||
// pack();
|
||||
setVisible(true);
|
||||
java.awt.EventQueue.invokeLater(this::repaint);
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void build() {
|
||||
pane.removeAll();
|
||||
|
||||
pane.add(new EJBoxNoStretch(LINE_AXIS, false, true) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
|
||||
add(Box.createHorizontalGlue());
|
||||
add(resetButton = new JButton("RESET") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(Box.createHorizontalStrut(10));
|
||||
add(new JButton("Fast Reset") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
resetFast();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(Box.createHorizontalStrut(10));
|
||||
add(floorClipButton = new JButton("Toggle Floor Clip") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
boolean[] state = server.humanPoseProcessor.getLegTweaksState();
|
||||
setFloorClipEnabled(!state[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
setFloorClipEnabled(
|
||||
server
|
||||
.getConfigManager()
|
||||
.getVrConfig()
|
||||
.getSkeleton()
|
||||
.getToggles()
|
||||
.get(SkeletonConfigToggles.FLOOR_CLIP.configKey)
|
||||
);
|
||||
|
||||
add(Box.createHorizontalStrut(10));
|
||||
add(skatingCorrectionButton = new JButton("Toggle Skating Correction") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
boolean[] state = server.humanPoseProcessor.getLegTweaksState();
|
||||
setSkatingReductionEnabled(!state[1]);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
setSkatingReductionEnabled(
|
||||
server
|
||||
.getConfigManager()
|
||||
.getVrConfig()
|
||||
.getSkeleton()
|
||||
.getToggles()
|
||||
.get(SkeletonConfigToggles.SKATING_CORRECTION.configKey)
|
||||
);
|
||||
|
||||
add(Box.createHorizontalGlue());
|
||||
add(new JButton("Record BVH") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (!server.getBvhRecorder().isRecording()) {
|
||||
setText("Stop Recording BVH...");
|
||||
server.getBvhRecorder().startRecording();
|
||||
} else {
|
||||
server.getBvhRecorder().endRecording();
|
||||
setText("Record BVH");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(Box.createHorizontalGlue());
|
||||
add(
|
||||
new JButton(
|
||||
"GUI Zoom (x" + StringUtils.prettyNumber(config.getZoom(), 2) + ")"
|
||||
) {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
guiZoom();
|
||||
setText(
|
||||
"GUI Zoom (x"
|
||||
+ StringUtils.prettyNumber(config.getZoom(), 2)
|
||||
+ ")"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
add(Box.createHorizontalStrut(10));
|
||||
add(new JButton("WiFi") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@SuppressWarnings("unused")
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
new WiFiWindow(VRServerGUI.this);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(Box.createHorizontalStrut(10));
|
||||
}
|
||||
});
|
||||
|
||||
pane.add(new EJBox(LINE_AXIS) {
|
||||
{
|
||||
setBorder(new EmptyBorder(i(5)));
|
||||
add(new EJBoxNoStretch(PAGE_AXIS, false, true) {
|
||||
{
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
JLabel l;
|
||||
add(l = new JLabel("Trackers list"));
|
||||
l.setFont(l.getFont().deriveFont(Font.BOLD));
|
||||
l.setAlignmentX(0.5f);
|
||||
add(trackersList);
|
||||
add(Box.createVerticalGlue());
|
||||
}
|
||||
});
|
||||
|
||||
add(new EJBoxNoStretch(PAGE_AXIS, false, true) {
|
||||
{
|
||||
setAlignmentY(TOP_ALIGNMENT);
|
||||
|
||||
JCheckBox debugCb;
|
||||
add(debugCb = new JCheckBox("Show debug information"));
|
||||
debugCb.setSelected(false);
|
||||
debugCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
trackersList.setDebug(debugCb.isSelected());
|
||||
}
|
||||
});
|
||||
|
||||
JLabel l;
|
||||
add(l = new JLabel("Body proportions"));
|
||||
l.setFont(l.getFont().deriveFont(Font.BOLD));
|
||||
l.setAlignmentX(0.5f);
|
||||
add(new SkeletonConfigGUI(server, VRServerGUI.this));
|
||||
add(Box.createVerticalStrut(10));
|
||||
if (server.hasBridge(WindowsNamedPipeBridge.class)) {
|
||||
WindowsNamedPipeBridge br = server
|
||||
.getVRBridge(WindowsNamedPipeBridge.class);
|
||||
add(l = new JLabel("SteamVR Trackers"));
|
||||
l.setFont(l.getFont().deriveFont(Font.BOLD));
|
||||
l.setAlignmentX(0.5f);
|
||||
add(l = new JLabel("Changes may require restart of SteamVR"));
|
||||
l.setFont(l.getFont().deriveFont(Font.ITALIC));
|
||||
l.setAlignmentX(0.5f);
|
||||
|
||||
add(new EJBagNoStretch(false, true) {
|
||||
{
|
||||
JCheckBox waistCb;
|
||||
add(waistCb = new JCheckBox("Waist"), c(1, 1));
|
||||
waistCb.setSelected(br.getShareSetting(TrackerRole.WAIST));
|
||||
waistCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server
|
||||
.queueTask(
|
||||
() -> br
|
||||
.changeShareSettings(
|
||||
TrackerRole.WAIST,
|
||||
waistCb.isSelected()
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
JCheckBox legsCb;
|
||||
add(legsCb = new JCheckBox("Feet"), c(2, 1));
|
||||
legsCb
|
||||
.setSelected(
|
||||
br.getShareSetting(TrackerRole.LEFT_FOOT)
|
||||
&& br.getShareSetting(TrackerRole.RIGHT_FOOT)
|
||||
);
|
||||
legsCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server.queueTask(() -> {
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.LEFT_FOOT,
|
||||
legsCb.isSelected()
|
||||
);
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.RIGHT_FOOT,
|
||||
legsCb.isSelected()
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
JCheckBox chestCb;
|
||||
add(chestCb = new JCheckBox("Chest"), c(1, 2));
|
||||
chestCb.setSelected(br.getShareSetting(TrackerRole.CHEST));
|
||||
chestCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server
|
||||
.queueTask(
|
||||
() -> br
|
||||
.changeShareSettings(
|
||||
TrackerRole.CHEST,
|
||||
chestCb.isSelected()
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
JCheckBox kneesCb;
|
||||
add(kneesCb = new JCheckBox("Knees"), c(2, 2));
|
||||
kneesCb
|
||||
.setSelected(
|
||||
br.getShareSetting(TrackerRole.LEFT_KNEE)
|
||||
&& br.getShareSetting(TrackerRole.RIGHT_KNEE)
|
||||
);
|
||||
kneesCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server.queueTask(() -> {
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.LEFT_KNEE,
|
||||
kneesCb.isSelected()
|
||||
);
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.RIGHT_KNEE,
|
||||
kneesCb.isSelected()
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
JCheckBox elbowsCb;
|
||||
add(elbowsCb = new JCheckBox("Elbows"), c(1, 3));
|
||||
elbowsCb
|
||||
.setSelected(
|
||||
br.getShareSetting(TrackerRole.LEFT_ELBOW)
|
||||
&& br.getShareSetting(TrackerRole.RIGHT_ELBOW)
|
||||
);
|
||||
elbowsCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server.queueTask(() -> {
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.LEFT_ELBOW,
|
||||
elbowsCb.isSelected()
|
||||
);
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.RIGHT_ELBOW,
|
||||
elbowsCb.isSelected()
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
JCheckBox handsCb;
|
||||
add(handsCb = new JCheckBox("Hands"), c(2, 3));
|
||||
handsCb
|
||||
.setSelected(
|
||||
br.getShareSetting(TrackerRole.LEFT_HAND)
|
||||
&& br.getShareSetting(TrackerRole.RIGHT_HAND)
|
||||
);
|
||||
handsCb.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
server.queueTask(() -> {
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.LEFT_HAND,
|
||||
handsCb.isSelected()
|
||||
);
|
||||
br
|
||||
.changeShareSettings(
|
||||
TrackerRole.RIGHT_HAND,
|
||||
handsCb.isSelected()
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
add(Box.createVerticalStrut(10));
|
||||
}
|
||||
|
||||
add(l = new JLabel("Trackers filtering"));
|
||||
l.setFont(l.getFont().deriveFont(Font.BOLD));
|
||||
l.setAlignmentX(0.5f);
|
||||
add(trackersFiltersGUI);
|
||||
|
||||
add(Box.createVerticalStrut(10));
|
||||
|
||||
add(new JLabel("Skeleton data"));
|
||||
add(skeletonList);
|
||||
add(Box.createVerticalGlue());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
pane.add(Box.createVerticalGlue());
|
||||
|
||||
refresh();
|
||||
|
||||
server.addOnTick(trackersList::updateTrackers);
|
||||
server.addOnTick(skeletonList::updateBones);
|
||||
}
|
||||
|
||||
// For now only changes font size, but should change fixed components size
|
||||
// in
|
||||
// the future too
|
||||
private void guiZoom() {
|
||||
if (config.getZoom() <= 1.0f) {
|
||||
config.setZoom(1.5f);
|
||||
} else if (config.getZoom() <= 1.5f) {
|
||||
config.setZoom(1.75f);
|
||||
} else if (config.getZoom() <= 1.75f) {
|
||||
config.setZoom(2f);
|
||||
} else if (config.getZoom() <= 2.0f) {
|
||||
config.setZoom(2.5f);
|
||||
} else {
|
||||
config.setZoom(1f);
|
||||
}
|
||||
processNewZoom(config.getZoom() / WindowConfig.INITAL_ZOOM, pane);
|
||||
refresh();
|
||||
server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void resetFast() {
|
||||
server.resetTrackersYaw();
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void reset() {
|
||||
ButtonTimer.runTimer(resetButton, 3, "RESET", server::resetTrackers);
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void setSkatingReductionEnabled(Boolean value) {
|
||||
if (value == null)
|
||||
value = false;
|
||||
|
||||
skatingCorrectionButton.setBackground(value ? Color.GREEN : Color.RED);
|
||||
|
||||
skatingCorrectionButton
|
||||
.setText("Skating Correction: " + (value ? "ON" : "OFF"));
|
||||
|
||||
server.setSkatingReductionEnabled(value);
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void setFloorClipEnabled(Boolean value) {
|
||||
if (value == null)
|
||||
value = false;
|
||||
|
||||
floorClipButton.setBackground(value ? Color.GREEN : Color.RED);
|
||||
|
||||
// update the button
|
||||
floorClipButton.setText("Floor clip: " + (value ? "ON" : "OFF"));
|
||||
server.setFloorClipEnabled(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package dev.slimevr.gui;
|
||||
|
||||
import com.fazecast.jSerialComm.SerialPort;
|
||||
import dev.slimevr.gui.swing.EJBox;
|
||||
import dev.slimevr.serial.SerialListener;
|
||||
import io.eiren.util.ann.AWTThread;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.MouseInputAdapter;
|
||||
import java.awt.*;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
|
||||
|
||||
public class WiFiWindow extends JFrame implements SerialListener {
|
||||
|
||||
private static String savedSSID = "";
|
||||
private static String savedPassword = "";
|
||||
private final VRServerGUI gui;
|
||||
private JScrollPane scroll;
|
||||
JTextField ssidField;
|
||||
JPasswordField passwdField;
|
||||
JTextArea log;
|
||||
|
||||
public WiFiWindow(VRServerGUI gui) {
|
||||
super("WiFi Settings");
|
||||
this.gui = gui;
|
||||
|
||||
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
|
||||
|
||||
this.gui.server.getSerialHandler().addListener(this);
|
||||
|
||||
build();
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
private void build() {
|
||||
if (!this.gui.server.getSerialHandler().openSerial()) {
|
||||
JOptionPane
|
||||
.showMessageDialog(
|
||||
null,
|
||||
"Unable to open a serial connection. Check that your drivers are installed and nothing is using the serial port already (like Cura or VScode or another slimeVR server)",
|
||||
"SlimeVR: Serial connection error",
|
||||
JOptionPane.ERROR_MESSAGE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@AWTThread
|
||||
public void onSerialConnected(SerialPort port) {
|
||||
Container pane = getContentPane();
|
||||
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
|
||||
{
|
||||
add(
|
||||
new JLabel(
|
||||
"Tracker connected to "
|
||||
+ port.getSystemPortName()
|
||||
+ " ("
|
||||
+ port.getDescriptivePortName()
|
||||
+ ")"
|
||||
)
|
||||
);
|
||||
add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
add(new JButton("Reboot Tracker") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
gui.server.getSerialHandler().rebootRequest();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(new JButton("INFO") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
gui.server.getSerialHandler().infoRequest();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(new JButton("Factory Reset") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
gui.server.getSerialHandler().factoryResetRequest();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
add(
|
||||
scroll = new JScrollPane(
|
||||
log = new JTextArea(10, 20),
|
||||
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
|
||||
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||||
)
|
||||
);
|
||||
log.setLineWrap(true);
|
||||
scroll.setAutoscrolls(true);
|
||||
add(new JLabel("Enter WiFi credentials:"));
|
||||
add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
add(new JLabel("Network name:"));
|
||||
add(ssidField = new JTextField(savedSSID));
|
||||
}
|
||||
});
|
||||
add(new EJBox(BoxLayout.LINE_AXIS) {
|
||||
{
|
||||
add(new JLabel("Network password:"));
|
||||
passwdField = new JPasswordField(savedPassword);
|
||||
passwdField.setEchoChar('\u25cf');
|
||||
add(passwdField);
|
||||
add(new JCheckBox("Show Password") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
if (isSelected())
|
||||
passwdField.setEchoChar((char) 0);
|
||||
else
|
||||
passwdField.setEchoChar('\u25cf');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
add(new JButton("Send") {
|
||||
{
|
||||
addMouseListener(new MouseInputAdapter() {
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
savedSSID = ssidField.getText();
|
||||
savedPassword = new String(passwdField.getPassword());
|
||||
gui.server.getSerialHandler().setWifi(savedSSID, savedPassword);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
pack();
|
||||
setLocationRelativeTo(null);
|
||||
setVisible(true);
|
||||
java.awt.EventQueue.invokeLater(() -> {
|
||||
toFront();
|
||||
repaint();
|
||||
});
|
||||
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
|
||||
final WiFiWindow window = this;
|
||||
addWindowListener(new WindowAdapter() {
|
||||
@Override
|
||||
public void windowClosing(WindowEvent windowEvent) {
|
||||
gui.server.getSerialHandler().closeSerial();
|
||||
dispose();
|
||||
gui.server.getSerialHandler().removeListener(window);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@AWTThread
|
||||
public void onSerialDisconnected() {
|
||||
if (this.log == null)
|
||||
return;
|
||||
log.append("[SERVER] Serial port disconnected\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
@AWTThread
|
||||
public void onSerialLog(String str) {
|
||||
if (this.log == null)
|
||||
return;
|
||||
log.append(str);
|
||||
// log.setAutoscrolls(true);
|
||||
if (scroll != null) {
|
||||
JScrollBar vertical = scroll.getVerticalScrollBar();
|
||||
if ((vertical.getValue() + str.length() + 200) > vertical.getMaximum()) {
|
||||
vertical.setValue(vertical.getMaximum());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
|
||||
public class ButtonTimer {
|
||||
|
||||
private static final Timer timer = new Timer();
|
||||
|
||||
public static void runTimer(
|
||||
AbstractButton button,
|
||||
int seconds,
|
||||
String defaultText,
|
||||
Runnable runnable
|
||||
) {
|
||||
if (seconds <= 0) {
|
||||
button.setText(defaultText);
|
||||
runnable.run();
|
||||
} else {
|
||||
button.setText(String.valueOf(seconds));
|
||||
timer.schedule(new ButtonTimerTask(button, seconds - 1, defaultText, runnable), 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ButtonTimerTask extends TimerTask {
|
||||
|
||||
private final AbstractButton button;
|
||||
private final int seconds;
|
||||
private final String defaultText;
|
||||
private final Runnable runnable;
|
||||
|
||||
private ButtonTimerTask(
|
||||
AbstractButton button,
|
||||
int seconds,
|
||||
String defaultText,
|
||||
Runnable runnable
|
||||
) {
|
||||
this.button = button;
|
||||
this.seconds = seconds;
|
||||
this.defaultText = defaultText;
|
||||
this.runnable = runnable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
runTimer(button, seconds, defaultText, runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import java.awt.*;
|
||||
|
||||
|
||||
public class EJBag extends EJPanel {
|
||||
|
||||
public EJBag() {
|
||||
super(new GridBagLayout());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import java.awt.*;
|
||||
|
||||
|
||||
public class EJBagNoStretch extends EJPanel {
|
||||
|
||||
public EJBagNoStretch(boolean stretchVertical, boolean stretchHorizontal) {
|
||||
super(new EGridBagLayoutNoStretch(stretchVertical, stretchHorizontal));
|
||||
}
|
||||
|
||||
private static class EGridBagLayoutNoStretch extends GridBagLayout {
|
||||
|
||||
private final boolean stretchVertical;
|
||||
private final boolean stretchHorizontal;
|
||||
|
||||
public EGridBagLayoutNoStretch(boolean stretchVertical, boolean stretchHorizontal) {
|
||||
this.stretchVertical = stretchVertical;
|
||||
this.stretchHorizontal = stretchHorizontal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Dimension maximumLayoutSize(Container target) {
|
||||
Dimension pref = preferredLayoutSize(target);
|
||||
if (stretchVertical)
|
||||
pref.height = Integer.MAX_VALUE;
|
||||
if (stretchHorizontal)
|
||||
pref.width = Integer.MAX_VALUE;
|
||||
return pref;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
|
||||
public class EJBox extends EJPanel {
|
||||
|
||||
public EJBox(int layout) {
|
||||
super();
|
||||
setLayout(new BoxLayout(this, layout));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
|
||||
|
||||
public class EJBoxNoStretch extends EJPanel {
|
||||
|
||||
public EJBoxNoStretch(int layout, boolean stretchVertical, boolean stretchHorizontal) {
|
||||
super();
|
||||
setLayout(new BoxLayoutNoStretch(this, layout, stretchVertical, stretchHorizontal));
|
||||
}
|
||||
|
||||
private static class BoxLayoutNoStretch extends BoxLayout {
|
||||
|
||||
private final boolean stretchVertical;
|
||||
private final boolean stretchHorizontal;
|
||||
|
||||
public BoxLayoutNoStretch(
|
||||
Container target,
|
||||
int axis,
|
||||
boolean stretchVertical,
|
||||
boolean stretchHorizontal
|
||||
) {
|
||||
super(target, axis);
|
||||
this.stretchVertical = stretchVertical;
|
||||
this.stretchHorizontal = stretchHorizontal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Dimension maximumLayoutSize(Container target) {
|
||||
Dimension pref = preferredLayoutSize(target);
|
||||
if (stretchVertical)
|
||||
pref.height = Integer.MAX_VALUE;
|
||||
if (stretchHorizontal)
|
||||
pref.width = Integer.MAX_VALUE;
|
||||
return pref;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
|
||||
|
||||
public abstract class EJPanel extends JPanel {
|
||||
|
||||
public static boolean NEEDS_DOWNSCALE = false;
|
||||
public static float DOWNSCALE_FACTOR = 0.75f;
|
||||
|
||||
public EJPanel() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EJPanel(LayoutManager manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
public static void s(Component c, int width, int height) {
|
||||
if (NEEDS_DOWNSCALE) {
|
||||
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
|
||||
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
|
||||
}
|
||||
c.setSize(width, height);
|
||||
Dimension d = new Dimension(width, height);
|
||||
c.setPreferredSize(d);
|
||||
c.setMaximumSize(d);
|
||||
c.setMinimumSize(d);
|
||||
}
|
||||
|
||||
public static void minWidth(Component c, int width, int height) {
|
||||
if (NEEDS_DOWNSCALE) {
|
||||
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
|
||||
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
|
||||
}
|
||||
c.setPreferredSize(new Dimension(Short.MAX_VALUE, height));
|
||||
c.setMaximumSize(new Dimension(Short.MAX_VALUE, height));
|
||||
c.setMinimumSize(new Dimension(width, height));
|
||||
}
|
||||
|
||||
public static void minHeight(Component c, int width, int height) {
|
||||
if (NEEDS_DOWNSCALE) {
|
||||
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
|
||||
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
|
||||
}
|
||||
c.setPreferredSize(new Dimension(width, Short.MAX_VALUE));
|
||||
c.setMaximumSize(new Dimension(width, Short.MAX_VALUE));
|
||||
c.setMinimumSize(new Dimension(width, height));
|
||||
}
|
||||
|
||||
public static GridBagConstraints c(int x, int y) {
|
||||
GridBagConstraints c = new GridBagConstraints();
|
||||
c.gridx = x;
|
||||
c.gridy = y;
|
||||
return c;
|
||||
}
|
||||
|
||||
public static GridBagConstraints c(int x, int y, int padding) {
|
||||
GridBagConstraints c = new GridBagConstraints();
|
||||
c.gridx = x;
|
||||
c.gridy = y;
|
||||
c.insets = new Insets(padding, padding, padding, padding);
|
||||
return c;
|
||||
}
|
||||
|
||||
public static GridBagConstraints c(int x, int y, int padding, int anchor) {
|
||||
GridBagConstraints c = new GridBagConstraints();
|
||||
c.gridx = x;
|
||||
c.gridy = y;
|
||||
c.insets = new Insets(padding, padding, padding, padding);
|
||||
c.anchor = anchor;
|
||||
return c;
|
||||
}
|
||||
|
||||
public static GridBagConstraints c(int x, int y, Insets insets) {
|
||||
GridBagConstraints c = new GridBagConstraints();
|
||||
c.gridx = x;
|
||||
c.gridy = y;
|
||||
c.insets = insets;
|
||||
return c;
|
||||
}
|
||||
|
||||
public static GridBagConstraints s(GridBagConstraints c, int gridwidth, int gridheight) {
|
||||
c.gridwidth = gridwidth;
|
||||
c.gridheight = gridheight;
|
||||
return c;
|
||||
}
|
||||
|
||||
public static Insets i(int s) {
|
||||
return new Insets(s, s, s, s);
|
||||
}
|
||||
|
||||
public static Insets i(int h, int v) {
|
||||
return new Insets(v, h, v, h);
|
||||
}
|
||||
|
||||
public static Component padding(int width, int height) {
|
||||
return Box.createRigidArea(new Dimension(width, height));
|
||||
}
|
||||
|
||||
public static int fontSize(int baseSize) {
|
||||
return NEEDS_DOWNSCALE ? (int) Math.ceil(baseSize * DOWNSCALE_FACTOR) : baseSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dev.slimevr.gui.swing;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
|
||||
public class EJlabel extends JLabel {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.slimevr.hardware.magentometer;
|
||||
|
||||
import com.sun.jna.Library;
|
||||
import com.sun.jna.Native;
|
||||
|
||||
|
||||
public interface Magneto extends Library {
|
||||
|
||||
Magneto INSTANCE = Native.load("MagnetoLib", Magneto.class);
|
||||
|
||||
void calculate(double[] data, int nlines, double nxsrej, double hm, double[] B, double[] A_1);
|
||||
|
||||
double calculateHnorm(double[] data, int nlines);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package dev.slimevr.platform.windows;
|
||||
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import com.sun.jna.platform.win32.Kernel32;
|
||||
import com.sun.jna.platform.win32.WinBase;
|
||||
import com.sun.jna.platform.win32.WinError;
|
||||
import com.sun.jna.ptr.IntByReference;
|
||||
import dev.slimevr.Main;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.bridge.BridgeThread;
|
||||
import dev.slimevr.bridge.PipeState;
|
||||
import dev.slimevr.bridge.ProtobufBridge;
|
||||
import dev.slimevr.bridge.ProtobufMessages.ProtobufMessage;
|
||||
import dev.slimevr.bridge.ProtobufMessages.TrackerAdded;
|
||||
import dev.slimevr.config.BridgeConfig;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.Device;
|
||||
import dev.slimevr.vr.trackers.*;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class WindowsNamedPipeBridge extends ProtobufBridge<VRTracker> implements Runnable {
|
||||
|
||||
protected final String pipeName;
|
||||
protected final String bridgeSettingsKey;
|
||||
protected final Thread runnerThread;
|
||||
private final TrackerRole[] defaultRoles = new TrackerRole[] { TrackerRole.WAIST,
|
||||
TrackerRole.LEFT_FOOT, TrackerRole.RIGHT_FOOT };
|
||||
private final byte[] buffArray = new byte[2048];
|
||||
private final List<? extends ShareableTracker> shareableTrackers;
|
||||
protected WindowsPipe pipe;
|
||||
|
||||
private final BridgeConfig config;
|
||||
|
||||
public WindowsNamedPipeBridge(
|
||||
VRServer server,
|
||||
HMDTracker hmd,
|
||||
String bridgeSettingsKey,
|
||||
String bridgeName,
|
||||
String pipeName,
|
||||
List<? extends ShareableTracker> shareableTrackers
|
||||
) {
|
||||
super(bridgeName, hmd);
|
||||
this.pipeName = pipeName;
|
||||
this.bridgeSettingsKey = bridgeSettingsKey;
|
||||
this.runnerThread = new Thread(this, "Named pipe thread");
|
||||
this.shareableTrackers = shareableTrackers;
|
||||
this.config = server.getConfigManager().getVrConfig().getBrige(bridgeSettingsKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void startBridge() {
|
||||
for (TrackerRole role : defaultRoles) {
|
||||
changeShareSettings(
|
||||
role,
|
||||
this.config.getBridgeTrackerRole(role, true)
|
||||
);
|
||||
}
|
||||
for (ShareableTracker tr : shareableTrackers) {
|
||||
TrackerRole role = tr.getTrackerRole();
|
||||
changeShareSettings(
|
||||
role,
|
||||
this.config.getBridgeTrackerRole(role, false)
|
||||
);
|
||||
}
|
||||
runnerThread.start();
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public boolean getShareSetting(TrackerRole role) {
|
||||
for (ShareableTracker tr : shareableTrackers) {
|
||||
if (tr.getTrackerRole() == role) {
|
||||
return sharedTrackers.contains(tr);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public void changeShareSettings(TrackerRole role, boolean share) {
|
||||
if (role == null)
|
||||
return;
|
||||
for (ShareableTracker tr : shareableTrackers) {
|
||||
if (tr.getTrackerRole() == role) {
|
||||
if (share) {
|
||||
addSharedTracker(tr);
|
||||
} else {
|
||||
removeSharedTracker(tr);
|
||||
}
|
||||
config.setBridgeTrackerRole(role, share);
|
||||
Main.vrServer.getConfigManager().saveConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
protected VRTracker createNewTracker(TrackerAdded trackerAdded) {
|
||||
// Todo: We need the manufacturer
|
||||
Device device = Main.vrServer
|
||||
.getDeviceManager()
|
||||
.createDevice(
|
||||
trackerAdded.getTrackerName(),
|
||||
trackerAdded.getTrackerSerial(),
|
||||
"FeederAPP"
|
||||
);
|
||||
|
||||
VRTracker tracker = new VRTracker(
|
||||
trackerAdded.getTrackerId(),
|
||||
trackerAdded.getTrackerSerial(),
|
||||
trackerAdded.getTrackerName(),
|
||||
true,
|
||||
true,
|
||||
device
|
||||
);
|
||||
|
||||
device.getTrackers().add(tracker);
|
||||
Main.vrServer.getDeviceManager().addDevice(device);
|
||||
TrackerRole role = TrackerRole.getById(trackerAdded.getTrackerRole());
|
||||
if (role != null) {
|
||||
tracker.setBodyPosition(TrackerPosition.getByTrackerRole(role).orElse(null));
|
||||
}
|
||||
return tracker;
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
public void run() {
|
||||
try {
|
||||
createPipe();
|
||||
while (true) {
|
||||
boolean pipesUpdated = false;
|
||||
if (pipe.state == PipeState.CREATED) {
|
||||
tryOpeningPipe(pipe);
|
||||
}
|
||||
if (pipe.state == PipeState.OPEN) {
|
||||
pipesUpdated = updatePipe();
|
||||
updateMessageQueue();
|
||||
}
|
||||
if (pipe.state == PipeState.ERROR) {
|
||||
resetPipe();
|
||||
}
|
||||
if (!pipesUpdated) {
|
||||
try {
|
||||
Thread.sleep(5); // Up to 200Hz
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
protected boolean sendMessageReal(ProtobufMessage message) {
|
||||
if (pipe.state == PipeState.OPEN) {
|
||||
try {
|
||||
int size = message.getSerializedSize();
|
||||
CodedOutputStream os = CodedOutputStream.newInstance(buffArray, 4, size);
|
||||
message.writeTo(os);
|
||||
size += 4;
|
||||
buffArray[0] = (byte) (size & 0xFF);
|
||||
buffArray[1] = (byte) ((size >> 8) & 0xFF);
|
||||
buffArray[2] = (byte) ((size >> 16) & 0xFF);
|
||||
buffArray[3] = (byte) ((size >> 24) & 0xFF);
|
||||
if (Kernel32.INSTANCE.WriteFile(pipe.pipeHandle, buffArray, size, null, null)) {
|
||||
return true;
|
||||
}
|
||||
pipe.state = PipeState.ERROR;
|
||||
LogManager
|
||||
.severe("[" + bridgeName + "] Pipe error: " + Kernel32.INSTANCE.GetLastError());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean updatePipe() throws IOException {
|
||||
if (pipe.state == PipeState.OPEN) {
|
||||
boolean readAnything = false;
|
||||
IntByReference bytesAvailable = new IntByReference(0);
|
||||
while (
|
||||
Kernel32.INSTANCE
|
||||
.PeekNamedPipe(pipe.pipeHandle, buffArray, 4, null, bytesAvailable, null)
|
||||
) {
|
||||
if (bytesAvailable.getValue() >= 4) { // Got size
|
||||
int messageLength = (buffArray[3] << 24)
|
||||
| (buffArray[2] << 16)
|
||||
| (buffArray[1] << 8)
|
||||
| buffArray[0];
|
||||
if (messageLength > 1024) { // Overflow
|
||||
LogManager
|
||||
.severe(
|
||||
"["
|
||||
+ bridgeName
|
||||
+ "] Pipe overflow. Message length: "
|
||||
+ messageLength
|
||||
);
|
||||
pipe.state = PipeState.ERROR;
|
||||
return readAnything;
|
||||
}
|
||||
if (bytesAvailable.getValue() >= messageLength) {
|
||||
if (
|
||||
Kernel32.INSTANCE
|
||||
.ReadFile(
|
||||
pipe.pipeHandle,
|
||||
buffArray,
|
||||
messageLength,
|
||||
bytesAvailable,
|
||||
null
|
||||
)
|
||||
) {
|
||||
ProtobufMessage message = ProtobufMessage
|
||||
.parser()
|
||||
.parseFrom(buffArray, 4, messageLength - 4);
|
||||
messageReceived(message);
|
||||
readAnything = true;
|
||||
} else {
|
||||
pipe.state = PipeState.ERROR;
|
||||
LogManager
|
||||
.severe(
|
||||
"["
|
||||
+ bridgeName
|
||||
+ "] Pipe error: "
|
||||
+ Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
return readAnything;
|
||||
}
|
||||
} else {
|
||||
return readAnything; // Wait for more data
|
||||
}
|
||||
} else {
|
||||
return readAnything; // Wait for more data
|
||||
}
|
||||
}
|
||||
pipe.state = PipeState.ERROR;
|
||||
LogManager
|
||||
.severe("[" + bridgeName + "] Pipe error: " + Kernel32.INSTANCE.GetLastError());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void resetPipe() {
|
||||
WindowsPipe.safeDisconnect(pipe);
|
||||
pipe.state = PipeState.CREATED;
|
||||
Main.vrServer.queueTask(this::disconnected);
|
||||
}
|
||||
|
||||
private void createPipe() throws IOException {
|
||||
try {
|
||||
pipe = new WindowsPipe(
|
||||
Kernel32.INSTANCE
|
||||
.CreateNamedPipe(
|
||||
pipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX, // dwOpenMode
|
||||
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
|
||||
1, // nMaxInstances,
|
||||
1024 * 16, // nOutBufferSize,
|
||||
1024 * 16, // nInBufferSize,
|
||||
0, // nDefaultTimeOut,
|
||||
null
|
||||
),
|
||||
pipeName
|
||||
); // lpSecurityAttributes
|
||||
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " created");
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(pipe.pipeHandle))
|
||||
throw new IOException(
|
||||
"Can't open " + pipeName + " pipe: " + Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
LogManager.info("[" + bridgeName + "] Pipes are created");
|
||||
} catch (IOException e) {
|
||||
WindowsPipe.safeDisconnect(pipe);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryOpeningPipe(WindowsPipe pipe) {
|
||||
if (
|
||||
Kernel32.INSTANCE.ConnectNamedPipe(pipe.pipeHandle, null)
|
||||
|| Kernel32.INSTANCE.GetLastError() == WinError.ERROR_PIPE_CONNECTED
|
||||
) {
|
||||
pipe.state = PipeState.OPEN;
|
||||
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " is open");
|
||||
Main.vrServer.queueTask(this::reconnected);
|
||||
return true;
|
||||
}
|
||||
LogManager
|
||||
.info(
|
||||
"["
|
||||
+ bridgeName
|
||||
+ "] Error connecting to pipe "
|
||||
+ pipe.name
|
||||
+ ": "
|
||||
+ Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package dev.slimevr.platform.windows;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import com.sun.jna.platform.win32.Kernel32;
|
||||
import com.sun.jna.platform.win32.WinBase;
|
||||
import com.sun.jna.platform.win32.WinNT.HANDLE;
|
||||
import com.sun.jna.ptr.IntByReference;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.bridge.Bridge;
|
||||
import dev.slimevr.bridge.PipeState;
|
||||
import dev.slimevr.vr.trackers.*;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
|
||||
public class WindowsNamedPipeVRBridge extends Thread implements Bridge {
|
||||
|
||||
public static final String HMDPipeName = "\\\\.\\pipe\\HMDPipe";
|
||||
public static final String TrackersPipeName = "\\\\.\\pipe\\TrackPipe";
|
||||
public static final Charset ASCII = StandardCharsets.US_ASCII;
|
||||
private static final int MAX_COMMAND_LENGTH = 2048;
|
||||
private final byte[] buffArray = new byte[1024];
|
||||
private final StringBuilder commandBuilder = new StringBuilder(1024);
|
||||
private final StringBuilder sbBuffer = new StringBuilder(1024);
|
||||
private final Vector3f vBuffer = new Vector3f();
|
||||
private final Vector3f vBuffer2 = new Vector3f();
|
||||
private final Quaternion qBuffer = new Quaternion();
|
||||
private final Quaternion qBuffer2 = new Quaternion();
|
||||
private final HMDTracker hmd;
|
||||
private final List<WindowsPipe> trackerPipes;
|
||||
private final List<? extends Tracker> shareTrackers;
|
||||
private final List<ComputedTracker> internalTrackers;
|
||||
private final HMDTracker internalHMDTracker = new HMDTracker("internal://HMD");
|
||||
private final AtomicBoolean newHMDData = new AtomicBoolean(false);
|
||||
private WindowsPipe hmdPipe;
|
||||
|
||||
public WindowsNamedPipeVRBridge(
|
||||
HMDTracker hmd,
|
||||
List<? extends Tracker> shareTrackers,
|
||||
VRServer server
|
||||
) {
|
||||
super("Named Pipe VR Bridge");
|
||||
this.hmd = hmd;
|
||||
this.shareTrackers = new FastList<>(shareTrackers);
|
||||
this.trackerPipes = new FastList<>(shareTrackers.size());
|
||||
this.internalTrackers = new FastList<>(shareTrackers.size());
|
||||
for (Tracker t : shareTrackers) {
|
||||
ComputedTracker ct = new ComputedTracker(
|
||||
t.getTrackerId(),
|
||||
"internal://" + t.getName(),
|
||||
true,
|
||||
true
|
||||
);
|
||||
ct.setStatus(TrackerStatus.OK);
|
||||
this.internalTrackers.add(ct);
|
||||
}
|
||||
}
|
||||
|
||||
public static void safeDisconnect(WindowsPipe pipe) {
|
||||
try {
|
||||
if (pipe != null && pipe.pipeHandle != null)
|
||||
Kernel32.INSTANCE.DisconnectNamedPipe(pipe.pipeHandle);
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
createPipes();
|
||||
while (true) {
|
||||
waitForPipesToOpen();
|
||||
if (areAllPipesOpen()) {
|
||||
boolean hmdUpdated = updateHMD(); // Update at HMDs
|
||||
// frequency
|
||||
for (int i = 0; i < trackerPipes.size(); ++i) {
|
||||
updateTracker(i, hmdUpdated);
|
||||
}
|
||||
if (!hmdUpdated) {
|
||||
Thread.sleep(5); // Up to 200Hz
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataRead() {
|
||||
if (newHMDData.compareAndSet(true, false)) {
|
||||
hmd.position.set(internalHMDTracker.position);
|
||||
hmd.rotation.set(internalHMDTracker.rotation);
|
||||
hmd.dataTick();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dataWrite() {
|
||||
for (int i = 0; i < shareTrackers.size(); ++i) {
|
||||
Tracker t = shareTrackers.get(i);
|
||||
ComputedTracker it = this.internalTrackers.get(i);
|
||||
if (t.getPosition(vBuffer2))
|
||||
it.position.set(vBuffer2);
|
||||
if (t.getRotation(qBuffer2))
|
||||
it.rotation.set(qBuffer2);
|
||||
}
|
||||
}
|
||||
|
||||
private void waitForPipesToOpen() {
|
||||
if (hmdPipe.state == PipeState.CREATED) {
|
||||
if (tryOpeningPipe(hmdPipe))
|
||||
initHMDPipe(hmdPipe);
|
||||
}
|
||||
for (int i = 0; i < trackerPipes.size(); ++i) {
|
||||
WindowsPipe trackerPipe = trackerPipes.get(i);
|
||||
if (trackerPipe.state == PipeState.CREATED) {
|
||||
if (tryOpeningPipe(trackerPipe))
|
||||
initTrackerPipe(trackerPipe, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean updateHMD() throws IOException {
|
||||
if (hmdPipe.state == PipeState.OPEN) {
|
||||
IntByReference bytesAvailable = new IntByReference(0);
|
||||
if (
|
||||
Kernel32.INSTANCE
|
||||
.PeekNamedPipe(hmdPipe.pipeHandle, null, 0, null, bytesAvailable, null)
|
||||
) {
|
||||
if (bytesAvailable.getValue() > 0) {
|
||||
while (
|
||||
Kernel32.INSTANCE
|
||||
.ReadFile(
|
||||
hmdPipe.pipeHandle,
|
||||
buffArray,
|
||||
buffArray.length,
|
||||
bytesAvailable,
|
||||
null
|
||||
)
|
||||
) {
|
||||
int bytesRead = bytesAvailable.getValue();
|
||||
for (int i = 0; i < bytesRead; ++i) {
|
||||
char c = (char) buffArray[i];
|
||||
if (c == '\n') {
|
||||
executeHMDInput();
|
||||
commandBuilder.setLength(0);
|
||||
} else {
|
||||
commandBuilder.append(c);
|
||||
if (commandBuilder.length() >= MAX_COMMAND_LENGTH) {
|
||||
LogManager
|
||||
.severe(
|
||||
"[VRBridge] Command from the pipe is too long, flushing buffer"
|
||||
);
|
||||
commandBuilder.setLength(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bytesRead < buffArray.length)
|
||||
break; // Don't repeat, we read all available bytes
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void executeHMDInput() throws IOException {
|
||||
String[] split = commandBuilder.toString().split(" ");
|
||||
if (split.length < 7) {
|
||||
LogManager.severe("[VRBridge] Short HMD data received: " + commandBuilder);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
double x = Double.parseDouble(split[0]);
|
||||
double y = Double.parseDouble(split[1]);
|
||||
double z = Double.parseDouble(split[2]);
|
||||
double qw = Double.parseDouble(split[3]);
|
||||
double qx = Double.parseDouble(split[4]);
|
||||
double qy = Double.parseDouble(split[5]);
|
||||
double qz = Double.parseDouble(split[6]);
|
||||
|
||||
internalHMDTracker.position.set((float) x, (float) y, (float) z);
|
||||
internalHMDTracker.rotation.set((float) qx, (float) qy, (float) qz, (float) qw);
|
||||
internalHMDTracker.dataTick();
|
||||
newHMDData.set(true);
|
||||
} catch (NumberFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void updateTracker(int trackerId, boolean hmdUpdated) {
|
||||
Tracker sensor = internalTrackers.get(trackerId);
|
||||
if (sensor.getStatus().sendData) {
|
||||
WindowsPipe trackerPipe = trackerPipes.get(trackerId);
|
||||
if (hmdUpdated && trackerPipe.state == PipeState.OPEN) {
|
||||
sbBuffer.setLength(0);
|
||||
sensor.getPosition(vBuffer);
|
||||
sensor.getRotation(qBuffer);
|
||||
sbBuffer
|
||||
.append(vBuffer.x)
|
||||
.append(' ')
|
||||
.append(vBuffer.y)
|
||||
.append(' ')
|
||||
.append(vBuffer.z)
|
||||
.append(' ');
|
||||
sbBuffer
|
||||
.append(qBuffer.getW())
|
||||
.append(' ')
|
||||
.append(qBuffer.getX())
|
||||
.append(' ')
|
||||
.append(qBuffer.getY())
|
||||
.append(' ')
|
||||
.append(qBuffer.getZ())
|
||||
.append('\n');
|
||||
String str = sbBuffer.toString();
|
||||
System.arraycopy(str.getBytes(ASCII), 0, buffArray, 0, str.length());
|
||||
buffArray[str.length()] = '\0';
|
||||
IntByReference lpNumberOfBytesWritten = new IntByReference(0);
|
||||
Kernel32.INSTANCE
|
||||
.WriteFile(
|
||||
trackerPipe.pipeHandle,
|
||||
buffArray,
|
||||
str.length() + 1,
|
||||
lpNumberOfBytesWritten,
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initHMDPipe(WindowsPipe pipe) {
|
||||
hmd.setStatus(TrackerStatus.OK);
|
||||
}
|
||||
|
||||
private void initTrackerPipe(WindowsPipe pipe, int trackerId) {
|
||||
String trackerHello = this.shareTrackers.size() + " 0";
|
||||
System.arraycopy(trackerHello.getBytes(ASCII), 0, buffArray, 0, trackerHello.length());
|
||||
buffArray[trackerHello.length()] = '\0';
|
||||
IntByReference lpNumberOfBytesWritten = new IntByReference(0);
|
||||
Kernel32.INSTANCE
|
||||
.WriteFile(
|
||||
pipe.pipeHandle,
|
||||
buffArray,
|
||||
trackerHello.length() + 1,
|
||||
lpNumberOfBytesWritten,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
private boolean tryOpeningPipe(WindowsPipe pipe) {
|
||||
if (Kernel32.INSTANCE.ConnectNamedPipe(pipe.pipeHandle, null)) {
|
||||
pipe.state = PipeState.OPEN;
|
||||
LogManager.info("[VRBridge] Pipe " + pipe.name + " is open");
|
||||
return true;
|
||||
}
|
||||
|
||||
LogManager
|
||||
.info(
|
||||
"[VRBridge] Error connecting to pipe "
|
||||
+ pipe.name
|
||||
+ ": "
|
||||
+ Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean areAllPipesOpen() {
|
||||
if (hmdPipe == null || hmdPipe.state == PipeState.CREATED) {
|
||||
return false;
|
||||
}
|
||||
for (WindowsPipe pipe : trackerPipes) {
|
||||
if (pipe.state == PipeState.CREATED) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void createPipes() throws IOException {
|
||||
try {
|
||||
hmdPipe = new WindowsPipe(
|
||||
Kernel32.INSTANCE
|
||||
.CreateNamedPipe(
|
||||
HMDPipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX, // dwOpenMode
|
||||
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
|
||||
1, // nMaxInstances,
|
||||
1024 * 16, // nOutBufferSize,
|
||||
1024 * 16, // nInBufferSize,
|
||||
0, // nDefaultTimeOut,
|
||||
null
|
||||
),
|
||||
HMDPipeName
|
||||
); // lpSecurityAttributes
|
||||
LogManager.info("[VRBridge] Pipe " + hmdPipe.name + " created");
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(hmdPipe.pipeHandle))
|
||||
throw new IOException(
|
||||
"Can't open " + HMDPipeName + " pipe: " + Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
for (int i = 0; i < this.shareTrackers.size(); ++i) {
|
||||
String pipeName = TrackersPipeName + i;
|
||||
HANDLE pipeHandle = Kernel32.INSTANCE
|
||||
.CreateNamedPipe(
|
||||
pipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX, // dwOpenMode
|
||||
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
|
||||
1, // nMaxInstances,
|
||||
1024 * 16, // nOutBufferSize,
|
||||
1024 * 16, // nInBufferSize,
|
||||
0, // nDefaultTimeOut,
|
||||
null
|
||||
); // lpSecurityAttributes
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(pipeHandle))
|
||||
throw new IOException(
|
||||
"Can't open " + pipeName + " pipe: " + Kernel32.INSTANCE.GetLastError()
|
||||
);
|
||||
LogManager.info("[VRBridge] Pipe " + pipeName + " created");
|
||||
trackerPipes.add(new WindowsPipe(pipeHandle, pipeName));
|
||||
}
|
||||
LogManager.info("[VRBridge] Pipes are open");
|
||||
} catch (IOException e) {
|
||||
safeDisconnect(hmdPipe);
|
||||
for (WindowsPipe pipe : trackerPipes) {
|
||||
safeDisconnect(pipe);
|
||||
}
|
||||
trackerPipes.clear();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeSharedTracker(ShareableTracker tracker) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startBridge() {
|
||||
start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package dev.slimevr.platform.windows;
|
||||
|
||||
import com.sun.jna.platform.win32.Kernel32;
|
||||
import com.sun.jna.platform.win32.WinNT.HANDLE;
|
||||
import dev.slimevr.bridge.PipeState;
|
||||
|
||||
|
||||
public class WindowsPipe {
|
||||
|
||||
public final String name;
|
||||
public final HANDLE pipeHandle;
|
||||
public PipeState state = PipeState.CREATED;
|
||||
|
||||
public WindowsPipe(HANDLE pipeHandle, String name) {
|
||||
this.pipeHandle = pipeHandle;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static void safeDisconnect(WindowsPipe pipe) {
|
||||
try {
|
||||
if (pipe != null && pipe.pipeHandle != null)
|
||||
Kernel32.INSTANCE.DisconnectNamedPipe(pipe.pipeHandle);
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.posestreamer.BVHFileStream;
|
||||
import dev.slimevr.posestreamer.PoseDataStream;
|
||||
import dev.slimevr.posestreamer.ServerPoseStreamer;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class BVHRecorder {
|
||||
|
||||
private static final File bvhSaveDir = new File("BVH Recordings");
|
||||
private final ServerPoseStreamer poseStreamer;
|
||||
private PoseDataStream poseDataStream = null;
|
||||
|
||||
public BVHRecorder(VRServer server) {
|
||||
this.poseStreamer = new ServerPoseStreamer(server);
|
||||
}
|
||||
|
||||
public void startRecording() {
|
||||
File bvhFile = getBvhFile();
|
||||
if (bvhFile != null) {
|
||||
try {
|
||||
poseDataStream = new BVHFileStream(bvhFile);
|
||||
poseStreamer.setOutput(poseDataStream, 1000L / 100L);
|
||||
} catch (IOException e1) {
|
||||
LogManager
|
||||
.severe(
|
||||
"[BVH] Failed to create the recording file \"" + bvhFile.getPath() + "\"."
|
||||
);
|
||||
}
|
||||
} else {
|
||||
LogManager.severe("[BVH] Unable to get file to save to");
|
||||
}
|
||||
}
|
||||
|
||||
public void endRecording() {
|
||||
|
||||
try {
|
||||
poseStreamer.closeOutput(poseDataStream);
|
||||
} catch (Exception e1) {
|
||||
LogManager.severe("[BVH] Exception while closing poseDataStream", e1);
|
||||
} finally {
|
||||
poseDataStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
private File getBvhFile() {
|
||||
if (bvhSaveDir.isDirectory() || bvhSaveDir.mkdirs()) {
|
||||
File saveRecording;
|
||||
int recordingIndex = 1;
|
||||
do {
|
||||
saveRecording = new File(bvhSaveDir, "BVH-Recording" + recordingIndex++ + ".bvh");
|
||||
} while (saveRecording.exists());
|
||||
|
||||
return saveRecording;
|
||||
} else {
|
||||
LogManager
|
||||
.severe(
|
||||
"[BVH] Failed to create the recording directory \""
|
||||
+ bvhSaveDir.getPath()
|
||||
+ "\"."
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isRecording() {
|
||||
return poseDataStream != null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.vr.trackers.TrackerPosition;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
|
||||
public final class PoseFrameIO {
|
||||
|
||||
private PoseFrameIO() {
|
||||
// Do not allow instantiating
|
||||
}
|
||||
|
||||
public static boolean writeFrames(DataOutputStream outputStream, PoseFrames frames) {
|
||||
try {
|
||||
if (frames != null) {
|
||||
outputStream.writeInt(frames.getTrackerCount());
|
||||
for (PoseFrameTracker tracker : frames.getTrackers()) {
|
||||
outputStream.writeUTF(tracker.name);
|
||||
outputStream.writeInt(tracker.getFrameCount());
|
||||
for (int i = 0; i < tracker.getFrameCount(); i++) {
|
||||
TrackerFrame trackerFrame = tracker.safeGetFrame(i);
|
||||
if (trackerFrame == null) {
|
||||
outputStream.writeInt(0);
|
||||
continue;
|
||||
}
|
||||
|
||||
outputStream.writeInt(trackerFrame.getDataFlags());
|
||||
|
||||
if (trackerFrame.hasData(TrackerFrameData.DESIGNATION)) {
|
||||
outputStream.writeUTF(trackerFrame.designation.designation);
|
||||
}
|
||||
|
||||
if (trackerFrame.hasData(TrackerFrameData.ROTATION)) {
|
||||
outputStream.writeFloat(trackerFrame.rotation.getX());
|
||||
outputStream.writeFloat(trackerFrame.rotation.getY());
|
||||
outputStream.writeFloat(trackerFrame.rotation.getZ());
|
||||
outputStream.writeFloat(trackerFrame.rotation.getW());
|
||||
}
|
||||
|
||||
if (trackerFrame.hasData(TrackerFrameData.POSITION)) {
|
||||
outputStream.writeFloat(trackerFrame.position.getX());
|
||||
outputStream.writeFloat(trackerFrame.position.getY());
|
||||
outputStream.writeFloat(trackerFrame.position.getZ());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
outputStream.writeInt(0);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogManager.severe("Error writing frame to stream", e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean writeToFile(File file, PoseFrames frames) {
|
||||
try (
|
||||
DataOutputStream outputStream = new DataOutputStream(
|
||||
new BufferedOutputStream(new FileOutputStream(file))
|
||||
)
|
||||
) {
|
||||
writeFrames(outputStream, frames);
|
||||
} catch (Exception e) {
|
||||
LogManager.severe("Error writing frames to file", e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static PoseFrames readFrames(DataInputStream inputStream) {
|
||||
try {
|
||||
|
||||
int trackerCount = inputStream.readInt();
|
||||
FastList<PoseFrameTracker> trackers = new FastList<>(trackerCount);
|
||||
for (int i = 0; i < trackerCount; i++) {
|
||||
|
||||
String name = inputStream.readUTF();
|
||||
int trackerFrameCount = inputStream.readInt();
|
||||
FastList<TrackerFrame> trackerFrames = new FastList<>(
|
||||
trackerFrameCount
|
||||
);
|
||||
for (int j = 0; j < trackerFrameCount; j++) {
|
||||
int dataFlags = inputStream.readInt();
|
||||
|
||||
TrackerPosition designation = null;
|
||||
if (TrackerFrameData.DESIGNATION.check(dataFlags)) {
|
||||
designation = TrackerPosition
|
||||
.getByDesignation(inputStream.readUTF())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
Quaternion rotation = null;
|
||||
if (TrackerFrameData.ROTATION.check(dataFlags)) {
|
||||
float quatX = inputStream.readFloat();
|
||||
float quatY = inputStream.readFloat();
|
||||
float quatZ = inputStream.readFloat();
|
||||
float quatW = inputStream.readFloat();
|
||||
rotation = new Quaternion(quatX, quatY, quatZ, quatW);
|
||||
}
|
||||
|
||||
Vector3f position = null;
|
||||
if (TrackerFrameData.POSITION.check(dataFlags)) {
|
||||
float posX = inputStream.readFloat();
|
||||
float posY = inputStream.readFloat();
|
||||
float posZ = inputStream.readFloat();
|
||||
position = new Vector3f(posX, posY, posZ);
|
||||
}
|
||||
|
||||
trackerFrames.add(new TrackerFrame(designation, rotation, position));
|
||||
}
|
||||
|
||||
trackers.add(new PoseFrameTracker(name, trackerFrames));
|
||||
}
|
||||
|
||||
return new PoseFrames(trackers);
|
||||
} catch (Exception e) {
|
||||
LogManager.severe("Error reading frame from stream", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static PoseFrames readFromFile(File file) {
|
||||
try {
|
||||
return readFrames(
|
||||
new DataInputStream(new BufferedInputStream(new FileInputStream(file)))
|
||||
);
|
||||
} catch (Exception e) {
|
||||
LogManager.severe("Error reading frame from file", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.vr.processor.ComputedHumanPoseTracker;
|
||||
import dev.slimevr.vr.processor.skeleton.HumanSkeleton;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class PoseFrameSkeleton extends HumanSkeleton {
|
||||
|
||||
private int frameCursor = 0;
|
||||
|
||||
protected PoseFrameSkeleton(List<? extends ComputedHumanPoseTracker> computedTrackers) {
|
||||
super(computedTrackers);
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton(
|
||||
VRServer server,
|
||||
List<? extends ComputedHumanPoseTracker> computedTrackers
|
||||
) {
|
||||
super(server, computedTrackers);
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton(
|
||||
List<? extends Tracker> trackers,
|
||||
List<? extends ComputedHumanPoseTracker> computedTrackers
|
||||
) {
|
||||
super(trackers, computedTrackers);
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton(
|
||||
List<? extends Tracker> trackers,
|
||||
List<? extends ComputedHumanPoseTracker> computedTrackers,
|
||||
Map<SkeletonConfigOffsets, Float> configs,
|
||||
Map<SkeletonConfigOffsets, Float> altConfigs
|
||||
) {
|
||||
super(trackers, computedTrackers, configs, altConfigs);
|
||||
}
|
||||
|
||||
public PoseFrameSkeleton(
|
||||
List<? extends Tracker> trackers,
|
||||
List<? extends ComputedHumanPoseTracker> computedTrackers,
|
||||
Map<SkeletonConfigOffsets, Float> configs
|
||||
) {
|
||||
super(trackers, computedTrackers, configs);
|
||||
}
|
||||
|
||||
private int limitCursor() {
|
||||
if (frameCursor < 0) {
|
||||
frameCursor = 0;
|
||||
}
|
||||
|
||||
return frameCursor;
|
||||
}
|
||||
|
||||
public int setCursor(int index) {
|
||||
frameCursor = index;
|
||||
return limitCursor();
|
||||
}
|
||||
|
||||
public int incrementCursor(int increment) {
|
||||
frameCursor += increment;
|
||||
return limitCursor();
|
||||
}
|
||||
|
||||
public int incrementCursor() {
|
||||
return incrementCursor(1);
|
||||
}
|
||||
|
||||
public int getCursor() {
|
||||
return frameCursor;
|
||||
}
|
||||
|
||||
// Get tracker for specific frame
|
||||
@Override
|
||||
protected Tracker trackerPreUpdate(Tracker tracker) {
|
||||
if (tracker instanceof PoseFrameTracker) {
|
||||
// Return frame if available, otherwise return the original tracker
|
||||
TrackerFrame frame = ((PoseFrameTracker) tracker).safeGetFrame(frameCursor);
|
||||
return frame == null ? tracker : frame;
|
||||
}
|
||||
return tracker;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.config.TrackerConfig;
|
||||
import dev.slimevr.vr.Device;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import dev.slimevr.vr.trackers.TrackerPosition;
|
||||
import dev.slimevr.vr.trackers.TrackerStatus;
|
||||
import io.eiren.util.collections.FastList;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
|
||||
public class PoseFrameTracker implements Tracker, Iterable<TrackerFrame> {
|
||||
|
||||
public final String name;
|
||||
|
||||
private final FastList<TrackerFrame> frames;
|
||||
private final int trackerId = Tracker.getNextLocalTrackerId();
|
||||
private int frameCursor = 0;
|
||||
|
||||
public PoseFrameTracker(String name, FastList<TrackerFrame> frames) {
|
||||
if (frames == null) {
|
||||
throw new NullPointerException("frames must not be null");
|
||||
}
|
||||
|
||||
this.name = name != null ? name : "";
|
||||
this.frames = frames;
|
||||
}
|
||||
|
||||
public PoseFrameTracker(String name, int initialCapacity) {
|
||||
this(name, new FastList<>(initialCapacity));
|
||||
}
|
||||
|
||||
public PoseFrameTracker(Tracker parent, int initialCapacity) {
|
||||
this(parent.getName(), initialCapacity);
|
||||
}
|
||||
|
||||
public PoseFrameTracker(String name) {
|
||||
this(name, 5);
|
||||
}
|
||||
|
||||
public PoseFrameTracker(Tracker parent) {
|
||||
this(parent.getName());
|
||||
}
|
||||
|
||||
private int limitCursor() {
|
||||
if (frameCursor < 0 || frames.isEmpty()) {
|
||||
frameCursor = 0;
|
||||
} else if (frameCursor >= frames.size()) {
|
||||
frameCursor = frames.size() - 1;
|
||||
}
|
||||
|
||||
return frameCursor;
|
||||
}
|
||||
|
||||
public int setCursor(int index) {
|
||||
frameCursor = index;
|
||||
return limitCursor();
|
||||
}
|
||||
|
||||
public int incrementCursor(int increment) {
|
||||
frameCursor += increment;
|
||||
return limitCursor();
|
||||
}
|
||||
|
||||
public int incrementCursor() {
|
||||
return incrementCursor(1);
|
||||
}
|
||||
|
||||
public int getCursor() {
|
||||
return frameCursor;
|
||||
}
|
||||
|
||||
public int getFrameCount() {
|
||||
return frames.size();
|
||||
}
|
||||
|
||||
public TrackerFrame addFrame(int index, TrackerFrame trackerFrame) {
|
||||
frames.add(index, trackerFrame);
|
||||
return trackerFrame;
|
||||
}
|
||||
|
||||
public TrackerFrame addFrame(int index, Tracker tracker) {
|
||||
return addFrame(index, TrackerFrame.fromTracker(tracker));
|
||||
}
|
||||
|
||||
public TrackerFrame addFrame(TrackerFrame trackerFrame) {
|
||||
frames.add(trackerFrame);
|
||||
return trackerFrame;
|
||||
}
|
||||
|
||||
public TrackerFrame addFrame(Tracker tracker) {
|
||||
return addFrame(TrackerFrame.fromTracker(tracker));
|
||||
}
|
||||
|
||||
public TrackerFrame removeFrame(int index) {
|
||||
TrackerFrame trackerFrame = frames.remove(index);
|
||||
limitCursor();
|
||||
return trackerFrame;
|
||||
}
|
||||
|
||||
public TrackerFrame removeFrame(TrackerFrame trackerFrame) {
|
||||
frames.remove(trackerFrame);
|
||||
limitCursor();
|
||||
return trackerFrame;
|
||||
}
|
||||
|
||||
public void clearFrames() {
|
||||
frames.clear();
|
||||
limitCursor();
|
||||
}
|
||||
|
||||
public void fakeClearFrames() {
|
||||
frames.fakeClear();
|
||||
limitCursor();
|
||||
}
|
||||
|
||||
public TrackerFrame getFrame(int index) {
|
||||
return frames.get(index);
|
||||
}
|
||||
|
||||
public TrackerFrame getFrame() {
|
||||
return getFrame(frameCursor);
|
||||
}
|
||||
|
||||
public TrackerFrame safeGetFrame(int index) {
|
||||
try {
|
||||
return getFrame(index);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public TrackerFrame safeGetFrame() {
|
||||
return safeGetFrame(frameCursor);
|
||||
}
|
||||
|
||||
// #region Tracker Interface Implementation
|
||||
@Override
|
||||
public boolean getRotation(Quaternion store) {
|
||||
TrackerFrame frame = safeGetFrame();
|
||||
if (frame != null && frame.hasData(TrackerFrameData.ROTATION)) {
|
||||
store.set(frame.rotation);
|
||||
return true;
|
||||
}
|
||||
|
||||
store.set(Quaternion.IDENTITY);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getPosition(Vector3f store) {
|
||||
TrackerFrame frame = safeGetFrame();
|
||||
if (frame != null && frame.hasData(TrackerFrameData.POSITION)) {
|
||||
store.set(frame.position);
|
||||
return true;
|
||||
}
|
||||
|
||||
store.set(Vector3f.ZERO);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getAcceleration(Vector3f store) {
|
||||
store.set(0, 0, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackerStatus getStatus() {
|
||||
return TrackerStatus.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readConfig(TrackerConfig config) {
|
||||
throw new UnsupportedOperationException(
|
||||
"PoseFrameTracker does not implement configuration"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeConfig(TrackerConfig config) {
|
||||
throw new UnsupportedOperationException(
|
||||
"PoseFrameTracker does not implement configuration"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getConfidenceLevel() {
|
||||
return 1f;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetFull(Quaternion reference) {
|
||||
throw new UnsupportedOperationException("PoseFrameTracker does not implement calibration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetYaw(Quaternion reference) {
|
||||
throw new UnsupportedOperationException("PoseFrameTracker does not implement calibration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
throw new UnsupportedOperationException("PoseFrameTracker does not implement this method");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackerPosition getBodyPosition() {
|
||||
TrackerFrame frame = safeGetFrame();
|
||||
return frame == null ? null : frame.designation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBodyPosition(TrackerPosition position) {
|
||||
throw new UnsupportedOperationException(
|
||||
"PoseFrameTracker does not allow setting the body position"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean userEditable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasRotation() {
|
||||
TrackerFrame frame = safeGetFrame();
|
||||
return frame != null && frame.hasData(TrackerFrameData.ROTATION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPosition() {
|
||||
TrackerFrame frame = safeGetFrame();
|
||||
return frame != null && frame.hasData(TrackerFrameData.POSITION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isComputed() {
|
||||
return true;
|
||||
}
|
||||
// #endregion
|
||||
|
||||
@Override
|
||||
public Iterator<TrackerFrame> iterator() {
|
||||
return frames.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackerId() {
|
||||
return this.trackerId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackerNum() {
|
||||
return this.getTrackerId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tracker get() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCustomName() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import dev.slimevr.vr.trackers.TrackerPosition;
|
||||
import dev.slimevr.vr.trackers.TrackerUtils;
|
||||
import io.eiren.util.collections.FastList;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public final class PoseFrames implements Iterable<TrackerFrame[]> {
|
||||
|
||||
private final FastList<PoseFrameTracker> trackers;
|
||||
|
||||
/**
|
||||
* Creates a {@link PoseFrames} object with the provided list of
|
||||
* {@link PoseFrameTracker}s as the internal {@link PoseFrameTracker} list
|
||||
*
|
||||
* @see {@link FastList}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public PoseFrames(FastList<PoseFrameTracker> trackers) {
|
||||
this.trackers = trackers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link PoseFrames} object with the specified initial tracker
|
||||
* capacity
|
||||
*
|
||||
* @see {@link #PoseFrames(FastList)}
|
||||
*/
|
||||
public PoseFrames(int initialCapacity) {
|
||||
this.trackers = new FastList<>(initialCapacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link PoseFrames} object with the default initial tracker
|
||||
* capacity of {@code 5}
|
||||
*
|
||||
* @see {@link #PoseFrames(int)}
|
||||
*/
|
||||
public PoseFrames() {
|
||||
this(5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the provided {@link PoseFrameTracker} into the internal
|
||||
* {@link PoseFrameTracker} list
|
||||
*
|
||||
* @return The {@link PoseFrameTracker} provided
|
||||
* @see {@link List#add(Object)}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public PoseFrameTracker addTracker(PoseFrameTracker tracker) {
|
||||
trackers.add(tracker);
|
||||
return tracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the {@link PoseFrameTracker} at the specified index from the
|
||||
* internal {@link PoseFrameTracker} list
|
||||
*
|
||||
* @return The {@link PoseFrameTracker} previously at the specified index
|
||||
* @see {@link List#remove(int)}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public PoseFrameTracker removeTracker(int index) {
|
||||
return trackers.remove(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the specified {@link PoseFrameTracker} from the internal
|
||||
* {@link PoseFrameTracker} list
|
||||
*
|
||||
* @return {@code true} if the internal {@link PoseFrameTracker} list
|
||||
* contained the specified {@link PoseFrameTracker}
|
||||
* @see {@link List#remove(Object)}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public boolean removeTracker(PoseFrameTracker tracker) {
|
||||
return trackers.remove(tracker);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the internal {@link PoseFrameTracker} list
|
||||
*
|
||||
* @see {@link List#clear()}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public void clearTrackers() {
|
||||
trackers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fake clears the internal {@link PoseFrameTracker} list by setting the
|
||||
* size to zero
|
||||
*
|
||||
* @see {@link FastList#fakeClear()}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public void fakeClearTrackers() {
|
||||
trackers.fakeClear();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The number of contained {@link PoseFrameTracker} objects
|
||||
* @see {@link List#size()}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public int getTrackerCount() {
|
||||
return trackers.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A list of the contained {@link PoseFrameTracker} objects
|
||||
* @see {@link List}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public List<PoseFrameTracker> getTrackers() {
|
||||
return trackers;
|
||||
}
|
||||
|
||||
// #region Data Utilities
|
||||
|
||||
/**
|
||||
* A utility function to get the maximum Y value of the tracker associated
|
||||
* with the {@link TrackerPosition#HMD} tracker position
|
||||
*
|
||||
* @return The maximum Y value of the tracker associated with the
|
||||
* {@link TrackerPosition#HMD} tracker position
|
||||
* @see {@link #getMaxHeight(TrackerPosition)}, {@link TrackerPosition#HMD}
|
||||
*/
|
||||
public float getMaxHmdHeight() {
|
||||
return getMaxHeight(TrackerPosition.HMD);
|
||||
}
|
||||
|
||||
/**
|
||||
* A utility function to get the maximum Y value of the tracker associated
|
||||
* with the specified {@link TrackerPosition}
|
||||
*
|
||||
* @return The maximum Y value of the tracker associated with the specified
|
||||
* {@link TrackerPosition}
|
||||
* @see {@link TrackerPosition}
|
||||
*/
|
||||
public float getMaxHeight(TrackerPosition trackerPosition) {
|
||||
float maxHeight = 0f;
|
||||
|
||||
PoseFrameTracker hmd = TrackerUtils
|
||||
.findNonComputedHumanPoseTrackerForBodyPosition(trackers, trackerPosition);
|
||||
|
||||
if (hmd == null) {
|
||||
return maxHeight;
|
||||
}
|
||||
|
||||
for (TrackerFrame frame : hmd) {
|
||||
if (frame.hasData(TrackerFrameData.POSITION) && frame.position.y > maxHeight) {
|
||||
maxHeight = frame.position.y;
|
||||
}
|
||||
}
|
||||
|
||||
return maxHeight;
|
||||
}
|
||||
// #endregion
|
||||
|
||||
/**
|
||||
* @return The maximum number of {@link TrackerFrame}s contained within each
|
||||
* {@link PoseFrameTracker} in the internal {@link PoseFrameTracker} list
|
||||
* @see {@link PoseFrameTracker#getFrameCount()}, {@link PoseFrameTracker}
|
||||
*/
|
||||
public int getMaxFrameCount() {
|
||||
int maxFrames = 0;
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
if (tracker != null && tracker.getFrameCount() > maxFrames) {
|
||||
maxFrames = tracker.getFrameCount();
|
||||
}
|
||||
}
|
||||
|
||||
return maxFrames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the provided array buffer, get the {@link TrackerFrame}s contained
|
||||
* within each {@link PoseFrameTracker} in the internal
|
||||
* {@link PoseFrameTracker} list at the specified index
|
||||
*
|
||||
* @return The number of frames written to the buffer
|
||||
* @see {@link PoseFrameTracker#safeGetFrame(int)}, {@link TrackerFrame},
|
||||
* {@link PoseFrameTracker}
|
||||
*/
|
||||
public int getFrames(int frameIndex, TrackerFrame[] buffer) {
|
||||
int frameCount = 0;
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
if (tracker == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
TrackerFrame frame = tracker.safeGetFrame(frameIndex);
|
||||
|
||||
if (frame == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer[frameCount++] = frame;
|
||||
}
|
||||
|
||||
return frameCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the provided {@link List} buffer, get the {@link TrackerFrame}s
|
||||
* contained within each {@link PoseFrameTracker} in the internal
|
||||
* {@link PoseFrameTracker} list at the specified index
|
||||
*
|
||||
* @return The number of frames written to the buffer
|
||||
* @see {@link PoseFrameTracker#safeGetFrame(int)},
|
||||
* {@link List#set(int, Object)}, {@link TrackerFrame},
|
||||
* {@link PoseFrameTracker}
|
||||
*/
|
||||
public int getFrames(int frameIndex, List<TrackerFrame> buffer) {
|
||||
int frameCount = 0;
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
if (tracker == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
TrackerFrame frame = tracker.safeGetFrame(frameIndex);
|
||||
|
||||
if (frame == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer.set(frameCount++, frame);
|
||||
}
|
||||
|
||||
return frameCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The {@link TrackerFrame}s contained within each
|
||||
* {@link PoseFrameTracker} in the internal {@link PoseFrameTracker} list at
|
||||
* the specified index
|
||||
* @see {@link PoseFrameTracker#safeGetFrame(int)}, {@link TrackerFrame},
|
||||
* {@link PoseFrameTracker}
|
||||
*/
|
||||
public TrackerFrame[] getFrames(int frameIndex) {
|
||||
TrackerFrame[] trackerFrames = new TrackerFrame[trackers.size()];
|
||||
getFrames(frameIndex, trackerFrames);
|
||||
return trackerFrames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<TrackerFrame[]> iterator() {
|
||||
return new PoseFrameIterator(this);
|
||||
}
|
||||
|
||||
public class PoseFrameIterator implements Iterator<TrackerFrame[]> {
|
||||
|
||||
private final PoseFrames poseFrame;
|
||||
private final TrackerFrame[] trackerFrameBuffer;
|
||||
|
||||
private int cursor = 0;
|
||||
|
||||
public PoseFrameIterator(PoseFrames poseFrame) {
|
||||
this.poseFrame = poseFrame;
|
||||
trackerFrameBuffer = new TrackerFrame[poseFrame.getTrackerCount()];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (trackers.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (PoseFrameTracker tracker : trackers) {
|
||||
if (tracker != null && cursor < tracker.getFrameCount()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackerFrame[] next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
poseFrame.getFrames(cursor++, trackerFrameBuffer);
|
||||
|
||||
return trackerFrameBuffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
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;
|
||||
|
||||
|
||||
public class PoseRecorder {
|
||||
|
||||
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<PoseFrames> currentRecording;
|
||||
protected Consumer<RecordingProgress> currentFrameCallback;
|
||||
|
||||
protected final VRServer server;
|
||||
FastList<Pair<Tracker, PoseFrameTracker>> trackers = new FastList<>();
|
||||
|
||||
public PoseRecorder(VRServer server) {
|
||||
this.server = server;
|
||||
server.addOnTick(this::onTick);
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public void onTick() {
|
||||
if (numFrames <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
PoseFrames poseFrame = this.poseFrame;
|
||||
List<Pair<Tracker, PoseFrameTracker>> trackers = this.trackers;
|
||||
if (poseFrame == null || trackers == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (frameCursor >= numFrames) {
|
||||
// If done and hasn't yet, send finished recording
|
||||
stopFrameRecording();
|
||||
return;
|
||||
}
|
||||
|
||||
long curTime = System.currentTimeMillis();
|
||||
if (curTime < nextFrameTimeMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
nextFrameTimeMs += frameRecordingInterval;
|
||||
|
||||
// To prevent duplicate frames, make sure the frame time is always in
|
||||
// the future
|
||||
if (nextFrameTimeMs <= curTime) {
|
||||
nextFrameTimeMs = curTime + frameRecordingInterval;
|
||||
}
|
||||
|
||||
// Make sure it's synchronized since this is the server thread
|
||||
// interacting with
|
||||
// an unknown outside thread controlling this class
|
||||
synchronized (this) {
|
||||
// A stopped recording will be accounted for by an empty "trackers"
|
||||
// list
|
||||
int cursor = frameCursor++;
|
||||
for (Pair<Tracker, PoseFrameTracker> tracker : trackers) {
|
||||
// Add a frame for each tracker
|
||||
tracker.getRight().addFrame(cursor, tracker.getLeft());
|
||||
}
|
||||
|
||||
if (currentFrameCallback != null) {
|
||||
currentFrameCallback.accept(new RecordingProgress(frameCursor, numFrames));
|
||||
}
|
||||
|
||||
// If done, send finished recording
|
||||
if (frameCursor >= numFrames) {
|
||||
stopFrameRecording();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized Future<PoseFrames> startFrameRecording(int numFrames, long intervalMs) {
|
||||
return startFrameRecording(numFrames, intervalMs, server.getAllTrackers(), null);
|
||||
}
|
||||
|
||||
public synchronized Future<PoseFrames> startFrameRecording(
|
||||
int numFrames,
|
||||
long intervalMs,
|
||||
Consumer<RecordingProgress> frameCallback
|
||||
) {
|
||||
return startFrameRecording(numFrames, intervalMs, server.getAllTrackers(), frameCallback);
|
||||
}
|
||||
|
||||
public synchronized Future<PoseFrames> startFrameRecording(
|
||||
int numFrames,
|
||||
long intervalMs,
|
||||
List<Tracker> trackers
|
||||
) {
|
||||
return startFrameRecording(numFrames, intervalMs, trackers, null);
|
||||
}
|
||||
|
||||
public synchronized Future<PoseFrames> startFrameRecording(
|
||||
int numFrames,
|
||||
long intervalMs,
|
||||
List<Tracker> trackers,
|
||||
Consumer<RecordingProgress> frameCallback
|
||||
) {
|
||||
if (numFrames < 1) {
|
||||
throw new IllegalArgumentException("numFrames must at least have a value of 1");
|
||||
}
|
||||
if (intervalMs < 1) {
|
||||
throw new IllegalArgumentException("intervalMs must at least have a value of 1");
|
||||
}
|
||||
if (trackers == null) {
|
||||
throw new IllegalArgumentException("trackers must not be null");
|
||||
}
|
||||
if (trackers.isEmpty()) {
|
||||
throw new IllegalArgumentException("trackers must have at least one entry");
|
||||
}
|
||||
if (!isReadyToRecord()) {
|
||||
throw new IllegalStateException("PoseRecorder isn't ready to record!");
|
||||
}
|
||||
|
||||
cancelFrameRecording();
|
||||
|
||||
poseFrame = new PoseFrames(trackers.size());
|
||||
|
||||
// Update tracker list
|
||||
this.trackers.ensureCapacity(trackers.size());
|
||||
for (Tracker tracker : trackers) {
|
||||
// Ignore null and computed trackers
|
||||
if (tracker == null || tracker.isComputed()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create a tracker recording
|
||||
PoseFrameTracker poseFrameTracker = new PoseFrameTracker(tracker, numFrames);
|
||||
poseFrame.addTracker(poseFrameTracker);
|
||||
|
||||
// Pair tracker with recording
|
||||
this.trackers.add(Pair.of(tracker, poseFrameTracker));
|
||||
}
|
||||
|
||||
this.frameCursor = 0;
|
||||
this.numFrames = numFrames;
|
||||
|
||||
frameRecordingInterval = intervalMs;
|
||||
nextFrameTimeMs = -1L;
|
||||
|
||||
LogManager
|
||||
.info(
|
||||
"[PoseRecorder] Recording "
|
||||
+ numFrames
|
||||
+ " samples at a "
|
||||
+ intervalMs
|
||||
+ " ms frame interval"
|
||||
);
|
||||
|
||||
currentFrameCallback = frameCallback;
|
||||
currentRecording = new CompletableFuture<>();
|
||||
return currentRecording;
|
||||
}
|
||||
|
||||
public synchronized void stopFrameRecording() {
|
||||
CompletableFuture<PoseFrames> currentRecording = this.currentRecording;
|
||||
if (currentRecording != null && !currentRecording.isDone()) {
|
||||
// Stop the recording, returning the frames recorded
|
||||
currentRecording.complete(poseFrame);
|
||||
}
|
||||
|
||||
numFrames = -1;
|
||||
frameCursor = 0;
|
||||
trackers.clear();
|
||||
poseFrame = null;
|
||||
}
|
||||
|
||||
public synchronized void cancelFrameRecording() {
|
||||
CompletableFuture<PoseFrames> currentRecording = this.currentRecording;
|
||||
if (currentRecording != null && !currentRecording.isDone()) {
|
||||
// Cancel the current recording and return nothing
|
||||
currentRecording.cancel(true);
|
||||
}
|
||||
|
||||
numFrames = -1;
|
||||
frameCursor = 0;
|
||||
trackers.clear();
|
||||
poseFrame = null;
|
||||
}
|
||||
|
||||
public synchronized boolean isReadyToRecord() {
|
||||
return server.getTrackersCount() > 0;
|
||||
}
|
||||
|
||||
public synchronized boolean isRecording() {
|
||||
return numFrames > frameCursor;
|
||||
}
|
||||
|
||||
public synchronized boolean hasRecording() {
|
||||
return currentRecording != null;
|
||||
}
|
||||
|
||||
public synchronized Future<PoseFrames> getFramesAsync() {
|
||||
return currentRecording;
|
||||
}
|
||||
|
||||
public synchronized PoseFrames getFrames() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<PoseFrames> currentRecording = this.currentRecording;
|
||||
return currentRecording != null ? currentRecording.get() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.config.TrackerConfig;
|
||||
import dev.slimevr.vr.Device;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import dev.slimevr.vr.trackers.TrackerPosition;
|
||||
import dev.slimevr.vr.trackers.TrackerStatus;
|
||||
|
||||
|
||||
public final class TrackerFrame implements Tracker {
|
||||
|
||||
public final TrackerPosition designation;
|
||||
public final Quaternion rotation;
|
||||
public final Vector3f position;
|
||||
private final int trackerId = Tracker.getNextLocalTrackerId();
|
||||
private int dataFlags = 0;
|
||||
|
||||
public TrackerFrame(TrackerPosition designation, Quaternion rotation, Vector3f position) {
|
||||
this.designation = designation;
|
||||
if (designation != null) {
|
||||
dataFlags |= TrackerFrameData.DESIGNATION.flag;
|
||||
}
|
||||
|
||||
this.rotation = rotation;
|
||||
if (rotation != null) {
|
||||
dataFlags |= TrackerFrameData.ROTATION.flag;
|
||||
}
|
||||
|
||||
this.position = position;
|
||||
if (position != null) {
|
||||
dataFlags |= TrackerFrameData.POSITION.flag;
|
||||
}
|
||||
}
|
||||
|
||||
public static TrackerFrame fromTracker(Tracker tracker) {
|
||||
if (tracker == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If the tracker is not ready
|
||||
if (
|
||||
tracker.getStatus() != TrackerStatus.OK
|
||||
&& tracker.getStatus() != TrackerStatus.BUSY
|
||||
&& tracker.getStatus() != TrackerStatus.OCCLUDED
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If tracker has no data
|
||||
if (tracker.getBodyPosition() == null && !tracker.hasRotation() && !tracker.hasPosition()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Quaternion rotation = null;
|
||||
if (tracker.hasRotation()) {
|
||||
rotation = new Quaternion();
|
||||
if (!tracker.getRotation(rotation)) {
|
||||
// If getting the rotation failed, set it back to null
|
||||
rotation = null;
|
||||
}
|
||||
}
|
||||
|
||||
Vector3f position = null;
|
||||
if (tracker.hasPosition()) {
|
||||
position = new Vector3f();
|
||||
if (!tracker.getPosition(position)) {
|
||||
// If getting the position failed, set it back to null
|
||||
position = null;
|
||||
}
|
||||
}
|
||||
|
||||
return new TrackerFrame(tracker.getBodyPosition(), rotation, position);
|
||||
}
|
||||
|
||||
public int getDataFlags() {
|
||||
return dataFlags;
|
||||
}
|
||||
|
||||
public boolean hasData(TrackerFrameData flag) {
|
||||
return flag.check(dataFlags);
|
||||
}
|
||||
|
||||
// #region Tracker Interface Implementation
|
||||
@Override
|
||||
public boolean getRotation(Quaternion store) {
|
||||
if (hasData(TrackerFrameData.ROTATION)) {
|
||||
store.set(rotation);
|
||||
return true;
|
||||
}
|
||||
|
||||
store.set(Quaternion.IDENTITY);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getPosition(Vector3f store) {
|
||||
if (hasData(TrackerFrameData.POSITION)) {
|
||||
store.set(position);
|
||||
return true;
|
||||
}
|
||||
|
||||
store.set(Vector3f.ZERO);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getAcceleration(Vector3f store) {
|
||||
store.set(0, 0, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "TrackerFrame:/" + (designation != null ? designation.designation : "null");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackerStatus getStatus() {
|
||||
return TrackerStatus.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readConfig(TrackerConfig config) {
|
||||
throw new UnsupportedOperationException("TrackerFrame does not implement configuration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeConfig(TrackerConfig config) {
|
||||
throw new UnsupportedOperationException("TrackerFrame does not implement configuration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getConfidenceLevel() {
|
||||
return 1f;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetFull(Quaternion reference) {
|
||||
throw new UnsupportedOperationException("TrackerFrame does not implement calibration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetYaw(Quaternion reference) {
|
||||
throw new UnsupportedOperationException("TrackerFrame does not implement calibration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
throw new UnsupportedOperationException("TrackerFrame does not implement this method");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackerPosition getBodyPosition() {
|
||||
return designation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBodyPosition(TrackerPosition position) {
|
||||
throw new UnsupportedOperationException(
|
||||
"TrackerFrame does not allow setting the body position"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean userEditable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasRotation() {
|
||||
return hasData(TrackerFrameData.ROTATION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPosition() {
|
||||
return hasData(TrackerFrameData.POSITION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isComputed() {
|
||||
return true;
|
||||
}
|
||||
// #endregion
|
||||
|
||||
@Override
|
||||
public int getTrackerId() {
|
||||
return this.trackerId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackerNum() {
|
||||
return this.getTrackerId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tracker get() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCustomName() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.slimevr.poserecorder;
|
||||
|
||||
public enum TrackerFrameData {
|
||||
|
||||
DESIGNATION(0), ROTATION(1), POSITION(2),;
|
||||
|
||||
public final int flag;
|
||||
|
||||
TrackerFrameData(int id) {
|
||||
this.flag = 1 << id;
|
||||
}
|
||||
|
||||
public boolean check(int dataFlags) {
|
||||
return (dataFlags & this.flag) != 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import com.jme3.math.FastMath;
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Transform;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.vr.processor.TransformNode;
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
|
||||
public class BVHFileStream extends PoseDataStream {
|
||||
|
||||
private static final int LONG_MAX_VALUE_DIGITS = Long.toString(Long.MAX_VALUE).length();
|
||||
private static final float OFFSET_SCALE = 100f;
|
||||
private static final float POSITION_SCALE = 100f;
|
||||
private final BufferedWriter writer;
|
||||
private long frameCount = 0;
|
||||
private long frameCountOffset;
|
||||
|
||||
private float[] angleBuf = new float[3];
|
||||
private Quaternion rotBuf = new Quaternion();
|
||||
|
||||
private Skeleton wrappedSkeleton;
|
||||
private TransformNodeWrapper rootNode;
|
||||
|
||||
public BVHFileStream(OutputStream outputStream) {
|
||||
super(outputStream);
|
||||
writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
|
||||
}
|
||||
|
||||
public BVHFileStream(File file) throws FileNotFoundException {
|
||||
super(file);
|
||||
writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
|
||||
}
|
||||
|
||||
public BVHFileStream(String file) throws FileNotFoundException {
|
||||
super(file);
|
||||
writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
|
||||
}
|
||||
|
||||
private String getBufferedFrameCount(long frameCount) {
|
||||
String frameString = Long.toString(frameCount);
|
||||
int bufferCount = LONG_MAX_VALUE_DIGITS - frameString.length();
|
||||
|
||||
return bufferCount > 0 ? frameString + StringUtils.repeat(' ', bufferCount) : frameString;
|
||||
}
|
||||
|
||||
private TransformNodeWrapper wrapSkeletonIfNew(Skeleton skeleton) {
|
||||
TransformNodeWrapper wrapper = rootNode;
|
||||
|
||||
// If the wrapped skeleton is missing or the skeleton is updated
|
||||
if (wrapper == null || skeleton != wrappedSkeleton) {
|
||||
wrapper = wrapSkeleton(skeleton);
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
private TransformNodeWrapper wrapSkeleton(Skeleton skeleton) {
|
||||
TransformNodeWrapper wrapper = wrapSkeletonNodes(skeleton.getRootNode());
|
||||
|
||||
wrappedSkeleton = skeleton;
|
||||
rootNode = wrapper;
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
protected TransformNodeWrapper wrapSkeletonNodes(TransformNode rootNode) {
|
||||
return TransformNodeWrapper.wrapFullHierarchy(rootNode);
|
||||
}
|
||||
|
||||
private void writeNodeHierarchy(TransformNodeWrapper node) throws IOException {
|
||||
writeNodeHierarchy(node, 0);
|
||||
}
|
||||
|
||||
private void writeNodeHierarchy(TransformNodeWrapper node, int level) throws IOException {
|
||||
// Don't write end sites at populated nodes
|
||||
if (node.children.isEmpty() && node.getParent().children.size() > 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
String indentLevel = StringUtils.repeat("\t", level);
|
||||
String nextIndentLevel = indentLevel + "\t";
|
||||
|
||||
// Handle ends
|
||||
if (node.children.isEmpty()) {
|
||||
writer.write(indentLevel + "End Site\n");
|
||||
} else {
|
||||
writer.write((level > 0 ? indentLevel + "JOINT " : "ROOT ") + node.getName() + "\n");
|
||||
}
|
||||
writer.write(indentLevel + "{\n");
|
||||
|
||||
// Ignore the root offset and original root offset
|
||||
if (level > 0 && node.wrappedNode.getParent() != null) {
|
||||
Vector3f offset = node.localTransform.getTranslation();
|
||||
float reverseMultiplier = node.hasReversedHierarchy() ? -1 : 1;
|
||||
writer
|
||||
.write(
|
||||
nextIndentLevel
|
||||
+ "OFFSET "
|
||||
+ offset.getX() * OFFSET_SCALE * reverseMultiplier
|
||||
+ " "
|
||||
+ offset.getY() * OFFSET_SCALE * reverseMultiplier
|
||||
+ " "
|
||||
+ offset.getZ() * OFFSET_SCALE * reverseMultiplier
|
||||
+ "\n"
|
||||
);
|
||||
} else {
|
||||
writer.write(nextIndentLevel + "OFFSET 0.0 0.0 0.0\n");
|
||||
}
|
||||
|
||||
// Handle ends
|
||||
if (!node.children.isEmpty()) {
|
||||
// Only give position for root
|
||||
if (level > 0) {
|
||||
writer.write(nextIndentLevel + "CHANNELS 3 Zrotation Xrotation Yrotation\n");
|
||||
} else {
|
||||
writer
|
||||
.write(
|
||||
nextIndentLevel
|
||||
+ "CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n"
|
||||
);
|
||||
}
|
||||
|
||||
for (TransformNodeWrapper childNode : node.children) {
|
||||
writeNodeHierarchy(childNode, level + 1);
|
||||
}
|
||||
}
|
||||
|
||||
writer.write(indentLevel + "}\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeHeader(Skeleton skeleton, PoseStreamer streamer) throws IOException {
|
||||
if (skeleton == null) {
|
||||
throw new NullPointerException("skeleton must not be null");
|
||||
}
|
||||
if (streamer == null) {
|
||||
throw new NullPointerException("streamer must not be null");
|
||||
}
|
||||
|
||||
writer.write("HIERARCHY\n");
|
||||
writeNodeHierarchy(wrapSkeletonIfNew(skeleton));
|
||||
|
||||
writer.write("MOTION\n");
|
||||
writer.write("Frames: ");
|
||||
|
||||
// Get frame offset for finishing writing the file
|
||||
if (outputStream instanceof FileOutputStream fileOutputStream) {
|
||||
// Flush buffer to get proper offset
|
||||
writer.flush();
|
||||
frameCountOffset = fileOutputStream.getChannel().position();
|
||||
}
|
||||
|
||||
writer.write(getBufferedFrameCount(frameCount) + "\n");
|
||||
|
||||
// Frame time in seconds
|
||||
writer.write("Frame Time: " + (streamer.getFrameInterval() / 1000d) + "\n");
|
||||
}
|
||||
|
||||
// Roughly based off code from
|
||||
// https://github.com/TrackLab/ViRe/blob/50a987eff4db31036b2ebaeb5a28983cd473f267/Assets/Scripts/BVH/BVHRecorder.cs
|
||||
private float[] quatToXyzAngles(Quaternion q, float[] angles) {
|
||||
if (angles == null) {
|
||||
angles = new float[3];
|
||||
} else if (angles.length != 3) {
|
||||
throw new IllegalArgumentException("Angles array must have three elements");
|
||||
}
|
||||
|
||||
float x = q.getX();
|
||||
float y = q.getY();
|
||||
float z = q.getZ();
|
||||
float w = q.getW();
|
||||
|
||||
// Roll (X)
|
||||
float sinrCosp = -2f * (x * y - w * z);
|
||||
float cosrCosp = w * w - x * x + y * y - z * z;
|
||||
angles[0] = FastMath.atan2(sinrCosp, cosrCosp);
|
||||
|
||||
// Pitch (Y)
|
||||
float sinp = 2f * (y * z + w * x);
|
||||
// Use 90 degrees if out of range
|
||||
angles[1] = FastMath.abs(sinp) >= 1f
|
||||
? FastMath.copysign(FastMath.PI / 2f, sinp)
|
||||
: FastMath
|
||||
.asin(sinp);
|
||||
|
||||
// Yaw (Z)
|
||||
float sinyCosp = -2f * (x * z - w * y);
|
||||
float cosyCosp = w * w - x * x - y * y + z * z;
|
||||
angles[2] = FastMath.atan2(sinyCosp, cosyCosp);
|
||||
|
||||
return angles;
|
||||
}
|
||||
|
||||
private void writeNodeHierarchyRotation(TransformNodeWrapper node, Quaternion inverseRootRot)
|
||||
throws IOException {
|
||||
Transform transform = node.worldTransform;
|
||||
|
||||
/*
|
||||
* if (node.hasReversedHierarchy()) { for (TransformNodeWrapper
|
||||
* childNode : node.children) { // If the hierarchy is fully reversed,
|
||||
* set the rotation for the upper bone if
|
||||
* (childNode.hasReversedHierarchy()) { transform =
|
||||
* childNode.worldTransform; break; } } }
|
||||
*/
|
||||
|
||||
rotBuf = transform.getRotation(rotBuf);
|
||||
|
||||
// Adjust to local rotation
|
||||
if (inverseRootRot != null) {
|
||||
rotBuf = inverseRootRot.mult(rotBuf, rotBuf);
|
||||
}
|
||||
|
||||
// Yaw (Z), roll (X), pitch (Y) (intrinsic)
|
||||
// angleBuf = rotBuf.toAngles(angleBuf);
|
||||
|
||||
// Roll (X), pitch (Y), yaw (Z) (intrinsic)
|
||||
angleBuf = quatToXyzAngles(rotBuf.normalizeLocal(), angleBuf);
|
||||
|
||||
// Output in order of roll (Z), pitch (X), yaw (Y) (extrinsic)
|
||||
writer
|
||||
.write(
|
||||
angleBuf[0] * FastMath.RAD_TO_DEG
|
||||
+ " "
|
||||
+ angleBuf[1] * FastMath.RAD_TO_DEG
|
||||
+ " "
|
||||
+ angleBuf[2] * FastMath.RAD_TO_DEG
|
||||
);
|
||||
|
||||
// Get inverse rotation for child local rotations
|
||||
if (!node.children.isEmpty()) {
|
||||
Quaternion inverseRot = transform.getRotation().inverse();
|
||||
for (TransformNodeWrapper childNode : node.children) {
|
||||
if (childNode.children.isEmpty()) {
|
||||
// If it's an end node, skip
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add spacing
|
||||
writer.write(" ");
|
||||
writeNodeHierarchyRotation(childNode, inverseRot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeFrame(Skeleton skeleton) throws IOException {
|
||||
if (skeleton == null) {
|
||||
throw new NullPointerException("skeleton must not be null");
|
||||
}
|
||||
|
||||
TransformNodeWrapper rootNode = wrapSkeletonIfNew(skeleton);
|
||||
|
||||
Vector3f rootPos = rootNode.worldTransform.getTranslation();
|
||||
|
||||
// Write root position
|
||||
writer
|
||||
.write(
|
||||
rootPos.getX() * POSITION_SCALE
|
||||
+ " "
|
||||
+ rootPos.getY() * POSITION_SCALE
|
||||
+ " "
|
||||
+ rootPos.getZ() * POSITION_SCALE
|
||||
+ " "
|
||||
);
|
||||
writeNodeHierarchyRotation(rootNode, null);
|
||||
|
||||
writer.newLine();
|
||||
|
||||
frameCount++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeFooter(Skeleton skeleton) throws IOException {
|
||||
// Write the final frame count for files
|
||||
if (outputStream instanceof FileOutputStream fileOutputStream) {
|
||||
// Flush before anything else
|
||||
writer.flush();
|
||||
// Seek to the count offset
|
||||
fileOutputStream.getChannel().position(frameCountOffset);
|
||||
// Overwrite the count with a new value
|
||||
writer.write(Long.toString(frameCount));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
writer.close();
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
|
||||
public abstract class PoseDataStream implements AutoCloseable {
|
||||
|
||||
protected final OutputStream outputStream;
|
||||
protected boolean closed = false;
|
||||
|
||||
protected PoseDataStream(OutputStream outputStream) {
|
||||
this.outputStream = outputStream;
|
||||
}
|
||||
|
||||
protected PoseDataStream(File file) throws FileNotFoundException {
|
||||
this(new FileOutputStream(file));
|
||||
}
|
||||
|
||||
protected PoseDataStream(String file) throws FileNotFoundException {
|
||||
this(new FileOutputStream(file));
|
||||
}
|
||||
|
||||
public void writeHeader(Skeleton skeleton, PoseStreamer streamer) throws IOException {
|
||||
}
|
||||
|
||||
abstract void writeFrame(Skeleton skeleton) throws IOException;
|
||||
|
||||
public void writeFooter(Skeleton skeleton) throws IOException {
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
outputStream.close();
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.poserecorder.PoseFrameIO;
|
||||
import dev.slimevr.poserecorder.PoseFrameSkeleton;
|
||||
import dev.slimevr.poserecorder.PoseFrames;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
|
||||
public class PoseFrameStreamer extends PoseStreamer {
|
||||
|
||||
private final PoseFrames frames;
|
||||
|
||||
public PoseFrameStreamer(String path) {
|
||||
this(new File(path));
|
||||
}
|
||||
|
||||
public PoseFrameStreamer(File file) {
|
||||
this(PoseFrameIO.readFromFile(file));
|
||||
}
|
||||
|
||||
public PoseFrameStreamer(PoseFrames frames) {
|
||||
super(new PoseFrameSkeleton(frames.getTrackers(), null));
|
||||
this.frames = frames;
|
||||
}
|
||||
|
||||
public PoseFrames getFrames() {
|
||||
return frames;
|
||||
}
|
||||
|
||||
public synchronized void streamAllFrames() {
|
||||
PoseFrameSkeleton skeleton = (PoseFrameSkeleton) this.skeleton;
|
||||
for (int i = 0; i < frames.getMaxFrameCount(); i++) {
|
||||
skeleton.setCursor(i);
|
||||
skeleton.updatePose();
|
||||
captureFrame();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class PoseStreamer {
|
||||
|
||||
protected long frameRecordingInterval = 60L;
|
||||
|
||||
protected Skeleton skeleton;
|
||||
protected PoseDataStream poseFileStream;
|
||||
|
||||
public PoseStreamer(Skeleton skeleton) {
|
||||
this.skeleton = skeleton;
|
||||
}
|
||||
|
||||
public synchronized void captureFrame() {
|
||||
// Make sure the stream is open before trying to write
|
||||
if (poseFileStream.isClosed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
poseFileStream.writeFrame(skeleton);
|
||||
} catch (Exception e) {
|
||||
// Handle any exceptions without crashing the program
|
||||
LogManager.severe("[PoseStreamer] Exception while saving frame", e);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized long getFrameInterval() {
|
||||
return frameRecordingInterval;
|
||||
}
|
||||
|
||||
public synchronized void setFrameInterval(long intervalMs) {
|
||||
if (intervalMs < 1) {
|
||||
throw new IllegalArgumentException("intervalMs must at least have a value of 1");
|
||||
}
|
||||
|
||||
this.frameRecordingInterval = intervalMs;
|
||||
}
|
||||
|
||||
public synchronized Skeleton getSkeleton() {
|
||||
return skeleton;
|
||||
}
|
||||
|
||||
public synchronized void setOutput(PoseDataStream poseFileStream, long intervalMs)
|
||||
throws IOException {
|
||||
setFrameInterval(intervalMs);
|
||||
setOutput(poseFileStream);
|
||||
}
|
||||
|
||||
public synchronized PoseDataStream getOutput() {
|
||||
return poseFileStream;
|
||||
}
|
||||
|
||||
public synchronized void setOutput(PoseDataStream poseFileStream) throws IOException {
|
||||
poseFileStream.writeHeader(skeleton, this);
|
||||
this.poseFileStream = poseFileStream;
|
||||
}
|
||||
|
||||
public synchronized void closeOutput() throws IOException {
|
||||
PoseDataStream poseFileStream = this.poseFileStream;
|
||||
|
||||
if (poseFileStream != null) {
|
||||
closeOutput(poseFileStream);
|
||||
this.poseFileStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void closeOutput(PoseDataStream poseFileStream) throws IOException {
|
||||
if (poseFileStream != null) {
|
||||
poseFileStream.writeFooter(skeleton);
|
||||
poseFileStream.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
|
||||
|
||||
public class ServerPoseStreamer extends TickPoseStreamer {
|
||||
|
||||
protected final VRServer server;
|
||||
|
||||
public ServerPoseStreamer(VRServer server) {
|
||||
super(null); // Skeleton is registered later
|
||||
this.server = server;
|
||||
|
||||
// Register callbacks/events
|
||||
server.addSkeletonUpdatedCallback(this::onSkeletonUpdated);
|
||||
server.addOnTick(this::onTick);
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public void onSkeletonUpdated(Skeleton skeleton) {
|
||||
this.skeleton = skeleton;
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
public void onTick() {
|
||||
super.doTick();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.vr.processor.TransformNode;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
|
||||
public class StdBVHFileStream extends BVHFileStream {
|
||||
|
||||
public StdBVHFileStream(OutputStream outputStream) {
|
||||
super(outputStream);
|
||||
}
|
||||
|
||||
public StdBVHFileStream(File file) throws FileNotFoundException {
|
||||
super(file);
|
||||
}
|
||||
|
||||
public StdBVHFileStream(String file) throws FileNotFoundException {
|
||||
super(file);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TransformNodeWrapper wrapSkeletonNodes(TransformNode rootNode) {
|
||||
TransformNode newRoot = getNodeFromHierarchy(rootNode, "Hip");
|
||||
if (newRoot == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TransformNodeWrapper.wrapFullHierarchy(newRoot);
|
||||
}
|
||||
|
||||
private TransformNode getNodeFromHierarchy(TransformNode node, String name) {
|
||||
if (node.getName().equalsIgnoreCase(name)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
for (TransformNode child : node.children) {
|
||||
TransformNode result = getNodeFromHierarchy(child, name);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import dev.slimevr.vr.processor.skeleton.Skeleton;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
public class TickPoseStreamer extends PoseStreamer {
|
||||
|
||||
protected long nextFrameTimeMs = -1L;
|
||||
|
||||
public TickPoseStreamer(Skeleton skeleton) {
|
||||
super(skeleton);
|
||||
}
|
||||
|
||||
public void doTick() {
|
||||
PoseDataStream poseFileStream = this.poseFileStream;
|
||||
if (poseFileStream == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Skeleton skeleton = this.skeleton;
|
||||
if (skeleton == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
long curTime = System.currentTimeMillis();
|
||||
if (curTime < nextFrameTimeMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
nextFrameTimeMs += frameRecordingInterval;
|
||||
|
||||
// To prevent duplicate frames, make sure the frame time is always in
|
||||
// the future
|
||||
if (nextFrameTimeMs <= curTime) {
|
||||
nextFrameTimeMs = curTime + frameRecordingInterval;
|
||||
}
|
||||
|
||||
captureFrame();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void setOutput(PoseDataStream poseFileStream) throws IOException {
|
||||
super.setOutput(poseFileStream);
|
||||
nextFrameTimeMs = -1L; // Reset the frame timing
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package dev.slimevr.posestreamer;
|
||||
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Transform;
|
||||
import dev.slimevr.vr.processor.TransformNode;
|
||||
import io.eiren.util.collections.FastList;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class TransformNodeWrapper {
|
||||
|
||||
public final TransformNode wrappedNode;
|
||||
public final Transform localTransform;
|
||||
public final Transform worldTransform;
|
||||
public final List<TransformNodeWrapper> children;
|
||||
protected String name;
|
||||
protected TransformNodeWrapper parent;
|
||||
private boolean reversedHierarchy = false;
|
||||
|
||||
public TransformNodeWrapper(
|
||||
TransformNode nodeToWrap,
|
||||
String name,
|
||||
boolean reversedHierarchy,
|
||||
int initialChildCapacity
|
||||
) {
|
||||
this.wrappedNode = nodeToWrap;
|
||||
|
||||
this.name = name;
|
||||
|
||||
this.localTransform = nodeToWrap.localTransform;
|
||||
this.worldTransform = nodeToWrap.worldTransform;
|
||||
|
||||
this.reversedHierarchy = reversedHierarchy;
|
||||
|
||||
this.children = new FastList<>(initialChildCapacity);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(TransformNode nodeToWrap, String name, int initialChildCapacity) {
|
||||
this(nodeToWrap, name, false, initialChildCapacity);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(TransformNode nodeToWrap, String name) {
|
||||
this(nodeToWrap, name, false, 5);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(
|
||||
TransformNode nodeToWrap,
|
||||
boolean reversedHierarchy,
|
||||
int initialChildCapacity
|
||||
) {
|
||||
this(nodeToWrap, nodeToWrap.getName(), reversedHierarchy, initialChildCapacity);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(TransformNode nodeToWrap, boolean reversedHierarchy) {
|
||||
this(nodeToWrap, nodeToWrap.getName(), reversedHierarchy, 5);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(TransformNode nodeToWrap, int initialChildCapacity) {
|
||||
this(nodeToWrap, nodeToWrap.getName(), initialChildCapacity);
|
||||
}
|
||||
|
||||
public TransformNodeWrapper(TransformNode nodeToWrap) {
|
||||
this(nodeToWrap, nodeToWrap.getName());
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapFullHierarchyWithFakeRoot(TransformNode root) {
|
||||
// Allocate a "fake" root with appropriate size depending on connections
|
||||
// the
|
||||
// root has
|
||||
TransformNodeWrapper fakeRoot = new TransformNodeWrapper(
|
||||
root,
|
||||
root.getParent() != null ? 2 : 1
|
||||
);
|
||||
|
||||
// Attach downwards hierarchy to the fake root
|
||||
wrapNodeHierarchyDown(root, fakeRoot);
|
||||
|
||||
// Attach upwards hierarchy to the fake root
|
||||
fakeRoot.attachChild(wrapHierarchyUp(root));
|
||||
|
||||
return fakeRoot;
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapFullHierarchy(TransformNode root) {
|
||||
return wrapNodeHierarchyUp(wrapHierarchyDown(root));
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapHierarchyDown(TransformNode root) {
|
||||
return wrapNodeHierarchyDown(root, new TransformNodeWrapper(root, root.children.size()));
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapNodeHierarchyDown(
|
||||
TransformNode root,
|
||||
TransformNodeWrapper target
|
||||
) {
|
||||
for (TransformNode child : root.children) {
|
||||
target.attachChild(wrapHierarchyDown(child));
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapHierarchyUp(TransformNode root) {
|
||||
return wrapNodeHierarchyUp(
|
||||
new TransformNodeWrapper(root, true, root.getParent() != null ? 1 : 0)
|
||||
);
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapNodeHierarchyUp(TransformNodeWrapper root) {
|
||||
return wrapNodeHierarchyUp(root.wrappedNode, root);
|
||||
}
|
||||
|
||||
public static TransformNodeWrapper wrapNodeHierarchyUp(
|
||||
TransformNode root,
|
||||
TransformNodeWrapper target
|
||||
) {
|
||||
TransformNode parent = root.getParent();
|
||||
if (parent == null) {
|
||||
return target;
|
||||
}
|
||||
|
||||
// Flip the offset for these reversed nodes
|
||||
TransformNodeWrapper wrapper = new TransformNodeWrapper(
|
||||
parent,
|
||||
true,
|
||||
(parent.getParent() != null ? 1 : 0) + Math.max(0, parent.children.size() - 1)
|
||||
);
|
||||
target.attachChild(wrapper);
|
||||
|
||||
// Re-attach other children
|
||||
if (parent.children.size() > 1) {
|
||||
for (TransformNode child : parent.children) {
|
||||
// Skip the original node
|
||||
if (child == target.wrappedNode) {
|
||||
continue;
|
||||
}
|
||||
|
||||
wrapper.attachChild(wrapHierarchyDown(child));
|
||||
}
|
||||
}
|
||||
|
||||
// Continue up the hierarchy
|
||||
wrapNodeHierarchyUp(wrapper);
|
||||
// Return original node
|
||||
return target;
|
||||
}
|
||||
|
||||
public boolean hasReversedHierarchy() {
|
||||
return reversedHierarchy;
|
||||
}
|
||||
|
||||
public void setReversedHierarchy(boolean reversedHierarchy) {
|
||||
this.reversedHierarchy = reversedHierarchy;
|
||||
}
|
||||
|
||||
public boolean hasLocalRotation() {
|
||||
return wrappedNode.localRotation;
|
||||
}
|
||||
|
||||
public Quaternion calculateLocalRotation(Quaternion relativeTo, Quaternion result) {
|
||||
return calculateLocalRotationInverse(relativeTo.inverse(), result);
|
||||
}
|
||||
|
||||
public Quaternion calculateLocalRotationInverse(
|
||||
Quaternion inverseRelativeTo,
|
||||
Quaternion result
|
||||
) {
|
||||
if (result == null) {
|
||||
result = new Quaternion();
|
||||
}
|
||||
|
||||
return inverseRelativeTo.mult(worldTransform.getRotation(), result);
|
||||
}
|
||||
|
||||
public void attachChild(TransformNodeWrapper node) {
|
||||
if (node.parent != null) {
|
||||
throw new IllegalArgumentException("The child node must not already have a parent");
|
||||
}
|
||||
|
||||
this.children.add(node);
|
||||
node.parent = this;
|
||||
}
|
||||
|
||||
public TransformNodeWrapper getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import solarxr_protocol.data_feed.DataFeedConfigT;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ConnectionContext {
|
||||
|
||||
private final List<DataFeedConfigT> dataFeedConfigList = new ArrayList<>();
|
||||
|
||||
// I did it in a separate array because it was more convenient than making a
|
||||
// parent object of the DataFeedConfigT
|
||||
// idk if it should be a concern or not, i think it is fine tbh
|
||||
// Futurabeast
|
||||
private final List<Long> dataFeedTimers = new ArrayList<>();
|
||||
|
||||
private final List<Integer> subscribedTopics = new ArrayList<>();
|
||||
|
||||
|
||||
private boolean useSerial = false;
|
||||
private boolean useAutoBone = false;
|
||||
|
||||
public List<DataFeedConfigT> getDataFeedConfigList() {
|
||||
return dataFeedConfigList;
|
||||
}
|
||||
|
||||
public List<Long> getDataFeedTimers() {
|
||||
return dataFeedTimers;
|
||||
}
|
||||
|
||||
public List<Integer> getSubscribedTopics() {
|
||||
return subscribedTopics;
|
||||
}
|
||||
|
||||
public boolean useSerial() {
|
||||
return useSerial;
|
||||
}
|
||||
|
||||
public void setUseSerial(boolean useSerial) {
|
||||
this.useSerial = useSerial;
|
||||
}
|
||||
|
||||
public boolean useAutoBone() {
|
||||
return useAutoBone;
|
||||
}
|
||||
|
||||
public void setUseAutoBone(boolean useAutoBone) {
|
||||
this.useAutoBone = useAutoBone;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import com.jme3.math.Quaternion;
|
||||
import com.jme3.math.Vector3f;
|
||||
import dev.slimevr.vr.Device;
|
||||
import dev.slimevr.vr.processor.skeleton.BoneInfo;
|
||||
import dev.slimevr.vr.trackers.*;
|
||||
import solarxr_protocol.data_feed.Bone;
|
||||
import solarxr_protocol.data_feed.DataFeedUpdate;
|
||||
import solarxr_protocol.data_feed.device_data.DeviceData;
|
||||
import solarxr_protocol.data_feed.device_data.DeviceDataMaskT;
|
||||
import solarxr_protocol.data_feed.tracker.TrackerData;
|
||||
import solarxr_protocol.data_feed.tracker.TrackerDataMaskT;
|
||||
import solarxr_protocol.data_feed.tracker.TrackerInfo;
|
||||
import solarxr_protocol.datatypes.DeviceId;
|
||||
import solarxr_protocol.datatypes.Ipv4Address;
|
||||
import solarxr_protocol.datatypes.Temperature;
|
||||
import solarxr_protocol.datatypes.TrackerId;
|
||||
import solarxr_protocol.datatypes.hardware_info.HardwareInfo;
|
||||
import solarxr_protocol.datatypes.hardware_info.HardwareStatus;
|
||||
import solarxr_protocol.datatypes.math.Quat;
|
||||
import solarxr_protocol.datatypes.math.Vec3f;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class DataFeedBuilder {
|
||||
|
||||
public static int createHardwareInfo(FlatBufferBuilder fbb, Device device) {
|
||||
Tracker tracker = device.getTrackers().get(0).get();
|
||||
|
||||
int nameOffset = device.getFirmwareVersion() != null
|
||||
? fbb.createString(device.getFirmwareVersion())
|
||||
: 0;
|
||||
|
||||
int manufacturerOffset = device.getManufacturer() != null
|
||||
? fbb.createString(device.getManufacturer())
|
||||
: 0;
|
||||
|
||||
HardwareInfo.startHardwareInfo(fbb);
|
||||
HardwareInfo.addFirmwareVersion(fbb, nameOffset);
|
||||
HardwareInfo.addManufacturer(fbb, manufacturerOffset);
|
||||
HardwareInfo
|
||||
.addIpAddress(
|
||||
fbb,
|
||||
Ipv4Address
|
||||
.createIpv4Address(
|
||||
fbb,
|
||||
ByteBuffer.wrap(device.getIpAddress().getAddress()).getInt()
|
||||
)
|
||||
);
|
||||
// BRUH MOMENT
|
||||
// TODO need support: HardwareInfo.addHardwareRevision(fbb,
|
||||
// hardwareRevisionOffset);
|
||||
// TODO need support: HardwareInfo.addDisplayName(fbb, de);
|
||||
|
||||
// TODO need support: HardwareInfo.addMcuId(device);
|
||||
return HardwareInfo.endHardwareInfo(fbb);
|
||||
}
|
||||
|
||||
public static int createTrackerId(FlatBufferBuilder fbb, Tracker tracker) {
|
||||
TrackerId.startTrackerId(fbb);
|
||||
|
||||
TrackerId.addTrackerNum(fbb, tracker.getTrackerNum());
|
||||
if (tracker.getDevice() != null)
|
||||
TrackerId.addDeviceId(fbb, DeviceId.createDeviceId(fbb, tracker.getDevice().getId()));
|
||||
|
||||
return TrackerId.endTrackerId(fbb);
|
||||
}
|
||||
|
||||
public static int createTrackerInfos(FlatBufferBuilder fbb, boolean infoMask, Tracker tracker) {
|
||||
|
||||
if (!infoMask)
|
||||
return 0;
|
||||
|
||||
int displayNameOffset = fbb.createString(tracker.getDisplayName());
|
||||
|
||||
int customNameOffset = tracker.getCustomName() != null
|
||||
? fbb.createString(tracker.getCustomName())
|
||||
: 0;
|
||||
|
||||
|
||||
TrackerInfo.startTrackerInfo(fbb);
|
||||
if (tracker.getBodyPosition() != null)
|
||||
TrackerInfo.addBodyPart(fbb, tracker.getBodyPosition().bodyPart);
|
||||
TrackerInfo.addEditable(fbb, tracker.userEditable());
|
||||
TrackerInfo.addComputed(fbb, tracker.isComputed());
|
||||
TrackerInfo.addDisplayName(fbb, displayNameOffset);
|
||||
TrackerInfo.addCustomName(fbb, customNameOffset);
|
||||
|
||||
// TODO need support: TrackerInfo.addImuType(fbb, tracker.im);
|
||||
// TODO need support: TrackerInfo.addPollRate(fbb, tracker.);
|
||||
|
||||
if (tracker instanceof IMUTracker imuTracker) {
|
||||
if (imuTracker.getMountingRotation() != null) {
|
||||
Quaternion quaternion = imuTracker.getMountingRotation();
|
||||
TrackerInfo
|
||||
.addMountingOrientation(
|
||||
fbb,
|
||||
Quat
|
||||
.createQuat(
|
||||
fbb,
|
||||
quaternion.getX(),
|
||||
quaternion.getY(),
|
||||
quaternion.getZ(),
|
||||
quaternion.getW()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
return TrackerInfo.endTrackerInfo(fbb);
|
||||
}
|
||||
|
||||
public static int createTrackerPosition(FlatBufferBuilder fbb, Tracker tracker) {
|
||||
Vector3f pos = new Vector3f();
|
||||
tracker.getPosition(pos);
|
||||
|
||||
return Vec3f.createVec3f(fbb, pos.x, pos.y, pos.z);
|
||||
}
|
||||
|
||||
public static int createTrackerRotation(FlatBufferBuilder fbb, Tracker tracker) {
|
||||
Quaternion quaternion = new Quaternion();
|
||||
tracker.getRotation(quaternion);
|
||||
|
||||
return Quat
|
||||
.createQuat(
|
||||
fbb,
|
||||
quaternion.getX(),
|
||||
quaternion.getY(),
|
||||
quaternion.getZ(),
|
||||
quaternion.getW()
|
||||
);
|
||||
}
|
||||
|
||||
public static int createTrackerTemperature(FlatBufferBuilder fbb, Tracker tracker) {
|
||||
if (!(tracker instanceof IMUTracker imuTracker))
|
||||
return 0;
|
||||
return Temperature.createTemperature(fbb, imuTracker.temperature);
|
||||
}
|
||||
|
||||
public static int createTrackerData(
|
||||
FlatBufferBuilder fbb,
|
||||
TrackerDataMaskT mask,
|
||||
Tracker tracker
|
||||
) {
|
||||
int trackerInfosOffset = DataFeedBuilder.createTrackerInfos(fbb, mask.getInfo(), tracker);
|
||||
int trackerIdOffset = DataFeedBuilder.createTrackerId(fbb, tracker);
|
||||
|
||||
TrackerData.startTrackerData(fbb);
|
||||
|
||||
TrackerData.addTrackerId(fbb, trackerIdOffset);
|
||||
|
||||
if (trackerInfosOffset != 0)
|
||||
TrackerData.addInfo(fbb, trackerInfosOffset);
|
||||
if (mask.getStatus())
|
||||
TrackerData.addStatus(fbb, tracker.getStatus().id + 1);
|
||||
if (mask.getPosition() && tracker.hasPosition())
|
||||
TrackerData.addPosition(fbb, DataFeedBuilder.createTrackerPosition(fbb, tracker));
|
||||
if (mask.getRotation() && tracker.hasRotation())
|
||||
TrackerData.addRotation(fbb, DataFeedBuilder.createTrackerRotation(fbb, tracker));
|
||||
if (mask.getTemp()) {
|
||||
int trackerTemperatureOffset = DataFeedBuilder.createTrackerTemperature(fbb, tracker);
|
||||
if (trackerTemperatureOffset != 0)
|
||||
TrackerData.addTemp(fbb, trackerTemperatureOffset);
|
||||
}
|
||||
|
||||
return TrackerData.endTrackerData(fbb);
|
||||
}
|
||||
|
||||
public static int createTrackersData(
|
||||
FlatBufferBuilder fbb,
|
||||
DeviceDataMaskT mask,
|
||||
Device device
|
||||
) {
|
||||
if (mask.getTrackerData() == null)
|
||||
return 0;
|
||||
|
||||
List<Integer> trackersOffsets = new ArrayList<>();
|
||||
|
||||
device
|
||||
.getTrackers()
|
||||
.forEach(
|
||||
(value) -> trackersOffsets
|
||||
.add(DataFeedBuilder.createTrackerData(fbb, mask.getTrackerData(), value))
|
||||
);
|
||||
|
||||
DeviceData.startTrackersVector(fbb, trackersOffsets.size());
|
||||
trackersOffsets.forEach(offset -> DeviceData.addTrackers(fbb, offset));
|
||||
return fbb.endVector();
|
||||
}
|
||||
|
||||
public static int createDeviceData(
|
||||
FlatBufferBuilder fbb,
|
||||
int id,
|
||||
DeviceDataMaskT mask,
|
||||
Device device
|
||||
) {
|
||||
if (!mask.getDeviceData())
|
||||
return 0;
|
||||
|
||||
if (device.getTrackers().size() <= 0)
|
||||
return 0;
|
||||
|
||||
Tracker tracker = device.getTrackers().get(0).get();
|
||||
|
||||
if (tracker == null)
|
||||
return 0;
|
||||
|
||||
HardwareStatus.startHardwareStatus(fbb);
|
||||
HardwareStatus.addErrorStatus(fbb, tracker.getStatus().id);
|
||||
|
||||
if (tracker instanceof TrackerWithTPS)
|
||||
HardwareStatus.addTps(fbb, (int) ((TrackerWithTPS) tracker).getTPS());
|
||||
|
||||
if (tracker instanceof TrackerWithBattery twb) {
|
||||
HardwareStatus.addBatteryVoltage(fbb, twb.getBatteryVoltage());
|
||||
HardwareStatus.addBatteryPctEstimate(fbb, (int) twb.getBatteryLevel());
|
||||
}
|
||||
|
||||
if (tracker instanceof TrackerWithWireless tww) {
|
||||
HardwareStatus.addPing(fbb, tww.getPing());
|
||||
HardwareStatus.addRssi(fbb, (short) tww.getSignalStrength());
|
||||
}
|
||||
|
||||
int hardwareDataOffset = HardwareStatus.endHardwareStatus(fbb);
|
||||
int hardwareInfoOffset = DataFeedBuilder.createHardwareInfo(fbb, device);
|
||||
int trackersOffset = DataFeedBuilder.createTrackersData(fbb, mask, device);
|
||||
|
||||
int nameOffset = device.getCustomName() != null
|
||||
? fbb.createString(device.getCustomName())
|
||||
: 0;
|
||||
|
||||
DeviceData.startDeviceData(fbb);
|
||||
DeviceData.addCustomName(fbb, nameOffset);
|
||||
DeviceData.addId(fbb, DeviceId.createDeviceId(fbb, id));
|
||||
DeviceData.addHardwareStatus(fbb, hardwareDataOffset);
|
||||
DeviceData.addHardwareInfo(fbb, hardwareInfoOffset);
|
||||
DeviceData.addTrackers(fbb, trackersOffset);
|
||||
|
||||
return DeviceData.endDeviceData(fbb);
|
||||
}
|
||||
|
||||
public static int createSyntheticTrackersData(
|
||||
FlatBufferBuilder fbb,
|
||||
TrackerDataMaskT trackerDataMaskT,
|
||||
List<Tracker> trackers
|
||||
) {
|
||||
if (trackerDataMaskT == null)
|
||||
return 0;
|
||||
|
||||
List<Integer> trackerOffsets = new ArrayList<>();
|
||||
|
||||
trackers
|
||||
.forEach(
|
||||
(tracker) -> trackerOffsets
|
||||
.add(DataFeedBuilder.createTrackerData(fbb, trackerDataMaskT, tracker))
|
||||
);
|
||||
|
||||
DataFeedUpdate.startSyntheticTrackersVector(fbb, trackerOffsets.size());
|
||||
trackerOffsets.forEach((tracker -> DataFeedUpdate.addSyntheticTrackers(fbb, tracker)));
|
||||
return fbb.endVector();
|
||||
}
|
||||
|
||||
public static int createDevicesData(
|
||||
FlatBufferBuilder fbb,
|
||||
DeviceDataMaskT deviceDataMaskT,
|
||||
List<Device> devices
|
||||
) {
|
||||
if (deviceDataMaskT == null)
|
||||
return 0;
|
||||
|
||||
int[] devicesDataOffsets = new int[devices.size()];
|
||||
for (int i = 0; i < devices.size(); i++) {
|
||||
Device device = devices.get(i);
|
||||
devicesDataOffsets[i] = DataFeedBuilder
|
||||
.createDeviceData(fbb, i, deviceDataMaskT, device);
|
||||
}
|
||||
|
||||
return DataFeedUpdate.createDevicesVector(fbb, devicesDataOffsets);
|
||||
}
|
||||
|
||||
public static int createBonesData(
|
||||
FlatBufferBuilder fbb,
|
||||
boolean shouldSend,
|
||||
List<BoneInfo> boneInfos
|
||||
) {
|
||||
if (!shouldSend) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var boneOffsets = new int[boneInfos.size()];
|
||||
for (var i = 0; i < boneInfos.size(); ++i) {
|
||||
var bi = boneInfos.get(i);
|
||||
|
||||
var headPosG = bi.tailNode.getParent().worldTransform.getTranslation();
|
||||
var rotG = bi.getGlobalRotation();
|
||||
|
||||
// TODO: figure out why this value is stale, so that we don't need
|
||||
// to recalculate it all the time, since thats not performant.
|
||||
bi.updateLength();
|
||||
var length = bi.length;
|
||||
|
||||
Bone.startBone(fbb);
|
||||
|
||||
var rotGOffset = Quat
|
||||
.createQuat(
|
||||
fbb,
|
||||
rotG.getX(),
|
||||
rotG.getY(),
|
||||
rotG.getZ(),
|
||||
rotG.getW()
|
||||
);
|
||||
Bone.addRotationG(fbb, rotGOffset);
|
||||
var headPosGOffset = Vec3f.createVec3f(fbb, headPosG.x, headPosG.y, headPosG.z);
|
||||
Bone.addHeadPositionG(fbb, headPosGOffset);
|
||||
Bone.addBodyPart(fbb, bi.boneType.bodyPart);
|
||||
Bone.addBoneLength(fbb, length);
|
||||
|
||||
boneOffsets[i] = Bone.endBone(fbb);
|
||||
}
|
||||
|
||||
return DataFeedUpdate.createBonesVector(fbb, boneOffsets);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import solarxr_protocol.MessageBundle;
|
||||
import solarxr_protocol.data_feed.*;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
public class DataFeedHandler extends ProtocolHandler<DataFeedMessageHeader> {
|
||||
|
||||
private final ProtocolAPI api;
|
||||
|
||||
public DataFeedHandler(ProtocolAPI api) {
|
||||
this.api = api;
|
||||
|
||||
registerPacketListener(DataFeedMessage.StartDataFeed, this::onStartDataFeed);
|
||||
registerPacketListener(DataFeedMessage.PollDataFeed, this::onPollDataFeedRequest);
|
||||
|
||||
this.api.server.addOnTick(this::sendDataFeedUpdate);
|
||||
}
|
||||
|
||||
private void onStartDataFeed(GenericConnection conn, DataFeedMessageHeader header) {
|
||||
StartDataFeed req = (StartDataFeed) header.message(new StartDataFeed());
|
||||
if (req == null)
|
||||
return;
|
||||
int dataFeeds = req.dataFeedsLength();
|
||||
|
||||
conn.getContext().getDataFeedConfigList().clear();
|
||||
for (int i = 0; i < dataFeeds; i++) {
|
||||
// Using the object api here because we need to copy from the buffer
|
||||
// anyway so
|
||||
// let's do it from here and send the reference to an arraylist
|
||||
DataFeedConfigT config = req.dataFeeds(i).unpack();
|
||||
conn.getContext().getDataFeedConfigList().add(config);
|
||||
conn.getContext().getDataFeedTimers().add(System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
private void onPollDataFeedRequest(
|
||||
GenericConnection conn,
|
||||
DataFeedMessageHeader messageHeader
|
||||
) {
|
||||
|
||||
PollDataFeed req = (PollDataFeed) messageHeader.message(new PollDataFeed());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(300);
|
||||
|
||||
int messageOffset = this.buildDatafeed(fbb, req.config().unpack());
|
||||
|
||||
DataFeedMessageHeader.startDataFeedMessageHeader(fbb);
|
||||
DataFeedMessageHeader.addMessage(fbb, messageOffset);
|
||||
DataFeedMessageHeader.addMessageType(fbb, DataFeedMessage.DataFeedUpdate);
|
||||
int headerOffset = DataFeedMessageHeader.endDataFeedMessageHeader(fbb);
|
||||
|
||||
MessageBundle.startDataFeedMsgsVector(fbb, 1);
|
||||
MessageBundle.addDataFeedMsgs(fbb, headerOffset);
|
||||
int datafeedMessagesOffset = fbb.endVector();
|
||||
|
||||
int packet = createMessage(fbb, datafeedMessagesOffset);
|
||||
fbb.finish(packet);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public int buildDatafeed(FlatBufferBuilder fbb, DataFeedConfigT config) {
|
||||
int devicesOffset = DataFeedBuilder
|
||||
.createDevicesData(
|
||||
fbb,
|
||||
config.getDataMask(),
|
||||
this.api.server
|
||||
.getDeviceManager()
|
||||
.getDevices()
|
||||
);
|
||||
int trackersOffset = DataFeedBuilder
|
||||
.createSyntheticTrackersData(
|
||||
fbb,
|
||||
config.getSyntheticTrackersMask(),
|
||||
this.api.server
|
||||
.getAllTrackers()
|
||||
.stream()
|
||||
.filter(tracker -> tracker.get().getDevice() == null)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
|
||||
var s = this.api.server.humanPoseProcessor.getSkeleton();
|
||||
int bonesOffset = DataFeedBuilder
|
||||
.createBonesData(
|
||||
fbb,
|
||||
config.getBoneMask(),
|
||||
s.currentBoneInfo
|
||||
);
|
||||
|
||||
return DataFeedUpdate.createDataFeedUpdate(fbb, devicesOffset, trackersOffset, bonesOffset);
|
||||
}
|
||||
|
||||
public void sendDataFeedUpdate() {
|
||||
long currTime = System.currentTimeMillis();
|
||||
|
||||
this.api.getAPIServers().forEach((server) -> server.getAPIConnections().forEach((conn) -> {
|
||||
FlatBufferBuilder fbb = null;
|
||||
|
||||
int configsCount = conn.getContext().getDataFeedConfigList().size();
|
||||
|
||||
int[] data = new int[configsCount];
|
||||
|
||||
for (int index = 0; index < configsCount; index++) {
|
||||
Long lastTimeSent = conn.getContext().getDataFeedTimers().get(index);
|
||||
DataFeedConfigT configT = conn.getContext().getDataFeedConfigList().get(index);
|
||||
if (currTime - lastTimeSent > configT.getMinimumTimeSinceLast()) {
|
||||
if (fbb == null) {
|
||||
// That way we create a buffer only when needed
|
||||
fbb = new FlatBufferBuilder(300);
|
||||
}
|
||||
|
||||
int messageOffset = this.buildDatafeed(fbb, configT);
|
||||
|
||||
DataFeedMessageHeader.startDataFeedMessageHeader(fbb);
|
||||
DataFeedMessageHeader.addMessage(fbb, messageOffset);
|
||||
DataFeedMessageHeader.addMessageType(fbb, DataFeedMessage.DataFeedUpdate);
|
||||
data[index] = DataFeedMessageHeader.endDataFeedMessageHeader(fbb);
|
||||
|
||||
conn.getContext().getDataFeedTimers().set(index, currTime);
|
||||
if (fbb != null) {
|
||||
int messages = MessageBundle.createDataFeedMsgsVector(fbb, data);
|
||||
int packet = createMessage(fbb, messages);
|
||||
fbb.finish(packet);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(GenericConnection conn, DataFeedMessageHeader message) {
|
||||
BiConsumer<GenericConnection, DataFeedMessageHeader> consumer = this.handlers[message
|
||||
.messageType()];
|
||||
if (consumer != null)
|
||||
consumer.accept(conn, message);
|
||||
else
|
||||
LogManager
|
||||
.info(
|
||||
"[ProtocolAPI] Unhandled Datafeed packet received id: " + message.messageType()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int messagesCount() {
|
||||
return DataFeedMessage.names.length;
|
||||
}
|
||||
|
||||
public int createMessage(FlatBufferBuilder fbb, int datafeedMessagesOffset) {
|
||||
MessageBundle.startMessageBundle(fbb);
|
||||
if (datafeedMessagesOffset > -1)
|
||||
MessageBundle.addDataFeedMsgs(fbb, datafeedMessagesOffset);
|
||||
return MessageBundle.endMessageBundle(fbb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
public interface GenericConnection {
|
||||
|
||||
UUID getConnectionId();
|
||||
|
||||
ConnectionContext getContext();
|
||||
|
||||
void send(ByteBuffer bytes);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import solarxr_protocol.pub_sub.TopicIdT;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
|
||||
// This class is so the HashMap referencing the TopicId as key works
|
||||
// it needs a unique hashcode based on the topicId and also an equals function
|
||||
// because equals hashcode does not mean equals strings
|
||||
public class HashedTopicId {
|
||||
|
||||
private final TopicIdT inner;
|
||||
private final int hashcode;
|
||||
|
||||
public HashedTopicId(TopicIdT topicIdT) {
|
||||
this.inner = topicIdT;
|
||||
this.hashcode = (inner.getAppName()
|
||||
+ "."
|
||||
+ inner.getOrganization()
|
||||
+ "."
|
||||
+ inner.getTopic()).hashCode();
|
||||
}
|
||||
|
||||
public TopicIdT getInner() {
|
||||
return inner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
HashedTopicId that = (HashedTopicId) o;
|
||||
return Objects.equals(inner.getOrganization(), that.getInner().getOrganization())
|
||||
&& Objects.equals(inner.getAppName(), that.getInner().getAppName())
|
||||
&& Objects.equals(inner.getTopic(), that.getInner().getTopic());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import solarxr_protocol.MessageBundle;
|
||||
import solarxr_protocol.data_feed.DataFeedMessageHeader;
|
||||
import solarxr_protocol.pub_sub.PubSubHeader;
|
||||
import solarxr_protocol.rpc.RpcMessageHeader;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ProtocolAPI {
|
||||
|
||||
public final VRServer server;
|
||||
public final RPCHandler rpcHandler;
|
||||
public final DataFeedHandler dataFeedHandler;
|
||||
public final PubSubHandler pubSubHandler;
|
||||
|
||||
private final List<ProtocolAPIServer> servers = new ArrayList<>();
|
||||
|
||||
public ProtocolAPI(VRServer server) {
|
||||
this.server = server;
|
||||
this.rpcHandler = new RPCHandler(this);
|
||||
this.dataFeedHandler = new DataFeedHandler(this);
|
||||
this.pubSubHandler = new PubSubHandler(this);
|
||||
}
|
||||
|
||||
public void onMessage(GenericConnection conn, ByteBuffer message) {
|
||||
MessageBundle messageBundle = MessageBundle.getRootAsMessageBundle(message);
|
||||
|
||||
try {
|
||||
for (int index = 0; index < messageBundle.dataFeedMsgsLength(); index++) {
|
||||
DataFeedMessageHeader header = messageBundle.dataFeedMsgsVector().get(index);
|
||||
this.dataFeedHandler.onMessage(conn, header);
|
||||
}
|
||||
|
||||
for (int index = 0; index < messageBundle.rpcMsgsLength(); index++) {
|
||||
RpcMessageHeader header = messageBundle.rpcMsgsVector().get(index);
|
||||
this.rpcHandler.onMessage(conn, header);
|
||||
}
|
||||
|
||||
for (int index = 0; index < messageBundle.pubSubMsgsLength(); index++) {
|
||||
PubSubHeader header = messageBundle.pubSubMsgsVector().get(index);
|
||||
this.pubSubHandler.onMessage(conn, header);
|
||||
}
|
||||
} catch (AssertionError e) {
|
||||
// Catch flatbuffer errors
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public List<ProtocolAPIServer> getAPIServers() {
|
||||
return servers;
|
||||
}
|
||||
|
||||
public void registerAPIServer(ProtocolAPIServer server) {
|
||||
this.servers.add(server);
|
||||
}
|
||||
|
||||
public void removeAPIServer(ProtocolAPIServer server) {
|
||||
this.servers.remove(server);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
|
||||
public interface ProtocolAPIServer {
|
||||
|
||||
Stream<GenericConnection> getAPIConnections();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
|
||||
public abstract class ProtocolHandler<H> {
|
||||
|
||||
public final BiConsumer<GenericConnection, H>[] handlers;
|
||||
|
||||
public ProtocolHandler() {
|
||||
this.handlers = new BiConsumer[this.messagesCount()];
|
||||
}
|
||||
|
||||
public abstract void onMessage(GenericConnection conn, H message);
|
||||
|
||||
public abstract int messagesCount();
|
||||
|
||||
public void registerPacketListener(byte packetType, BiConsumer<GenericConnection, H> consumer) {
|
||||
if (this.handlers[packetType] != null)
|
||||
this.handlers[packetType] = this.handlers[packetType].andThen(consumer);
|
||||
else
|
||||
this.handlers[packetType] = consumer;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import solarxr_protocol.MessageBundle;
|
||||
import solarxr_protocol.pub_sub.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
|
||||
public class PubSubHandler extends ProtocolHandler<PubSubHeader> {
|
||||
|
||||
private final ProtocolAPI api;
|
||||
|
||||
// Two ways maps for faster reading when handling lots of packets
|
||||
public HashMap<HashedTopicId, Integer> topicsHandle = new HashMap<>();
|
||||
public HashMap<Integer, HashedTopicId> handleTopics = new HashMap<>();
|
||||
|
||||
public AtomicInteger nextLocalHandle = new AtomicInteger();
|
||||
|
||||
public PubSubHandler(ProtocolAPI api) {
|
||||
super();
|
||||
this.api = api;
|
||||
|
||||
registerPacketListener(PubSubUnion.SubscriptionRequest, this::onSubscriptionRequest);
|
||||
registerPacketListener(PubSubUnion.TopicHandleRequest, this::onTopicHandleRequest);
|
||||
registerPacketListener(PubSubUnion.Message, this::onTopicMessage);
|
||||
}
|
||||
|
||||
private int getTopicHandle(TopicIdT topicIdT) {
|
||||
HashedTopicId hashedTopicId = new HashedTopicId(topicIdT);
|
||||
Integer handleT = topicsHandle.get(hashedTopicId);
|
||||
// if no handle exists for this topic id we create one and return it
|
||||
// anyway
|
||||
if (handleT == null) {
|
||||
handleT = nextLocalHandle.incrementAndGet();
|
||||
topicsHandle.put(hashedTopicId, handleT);
|
||||
handleTopics.put(handleT, hashedTopicId);
|
||||
}
|
||||
|
||||
return handleT;
|
||||
}
|
||||
|
||||
public void onSubscriptionRequest(GenericConnection conn, PubSubHeader messageHeader) {
|
||||
SubscriptionRequest req = (SubscriptionRequest) messageHeader.u(new SubscriptionRequest());
|
||||
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
int subHandle = -1;
|
||||
if (req.topicType() == Topic.TopicHandle) {
|
||||
TopicHandle handle = (TopicHandle) req.topic(new TopicHandle());
|
||||
if (handle != null && handleTopics.containsKey(handle.id()))
|
||||
subHandle = handle.id();
|
||||
} else if (req.topicType() == Topic.TopicId) {
|
||||
TopicId topicId = (TopicId) req.topic(new TopicId());
|
||||
if (topicId != null)
|
||||
subHandle = getTopicHandle(topicId.unpack());
|
||||
}
|
||||
|
||||
assert subHandle != -1;
|
||||
|
||||
final int finalSubHandle = subHandle;
|
||||
Optional<Integer> first = conn
|
||||
.getContext()
|
||||
.getSubscribedTopics()
|
||||
.stream()
|
||||
.filter((handle) -> handle == finalSubHandle)
|
||||
.findFirst();
|
||||
if (first.isEmpty()) {
|
||||
conn.getContext().getSubscribedTopics().add(finalSubHandle);
|
||||
}
|
||||
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
int topicIdOffset = TopicId.pack(fbb, handleTopics.get(finalSubHandle).getInner());
|
||||
int topicHandleOffset = TopicHandle.createTopicHandle(fbb, finalSubHandle);
|
||||
|
||||
int outbound = createMessage(
|
||||
fbb,
|
||||
PubSubUnion.TopicMapping,
|
||||
TopicMapping.createTopicMapping(fbb, topicIdOffset, topicHandleOffset)
|
||||
);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onTopicHandleRequest(GenericConnection conn, PubSubHeader messageHeader) {
|
||||
|
||||
TopicHandleRequest req = (TopicHandleRequest) messageHeader.u(new TopicHandleRequest());
|
||||
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
TopicHandleRequestT topicRequest = req.unpack();
|
||||
int handle = getTopicHandle(topicRequest.getId());
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
int topicIdOffset = TopicId.pack(fbb, topicRequest.getId());
|
||||
int topicHandleOffset = TopicHandle.createTopicHandle(fbb, handle);
|
||||
|
||||
int outbound = createMessage(
|
||||
fbb,
|
||||
PubSubUnion.TopicMapping,
|
||||
TopicMapping.createTopicMapping(fbb, topicIdOffset, topicHandleOffset)
|
||||
);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
|
||||
public void onTopicMessage(GenericConnection c, PubSubHeader messageHeader) {
|
||||
Message req = (Message) messageHeader.u(new Message());
|
||||
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
MessageT messageT = req.unpack();
|
||||
|
||||
int subHandle = 1;
|
||||
if (messageT.getTopic().getType() == Topic.TopicHandle) {
|
||||
subHandle = messageT.getTopic().asTopicHandle().getId();
|
||||
} else if (messageT.getTopic().getType() == Topic.TopicId) {
|
||||
subHandle = getTopicHandle(messageT.getTopic().asTopicId());
|
||||
}
|
||||
|
||||
|
||||
assert subHandle != -1;
|
||||
|
||||
int finalSubHandle = subHandle;
|
||||
|
||||
this.api.getAPIServers().forEach((server) -> {
|
||||
server.getAPIConnections().forEach((conn) -> {
|
||||
// Make sure that we are not sending a message to ourselves
|
||||
// And check that the receiver has subscribed to the topic
|
||||
if (
|
||||
!conn.getConnectionId().equals(c.getConnectionId())
|
||||
&& conn.getContext().getSubscribedTopics().contains(finalSubHandle)
|
||||
) {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
int outbound = createMessage(
|
||||
fbb,
|
||||
PubSubUnion.Message,
|
||||
Message.pack(fbb, messageT)
|
||||
);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(GenericConnection conn, PubSubHeader message) {
|
||||
BiConsumer<GenericConnection, PubSubHeader> consumer = this.handlers[message.uType()];
|
||||
if (consumer != null)
|
||||
consumer.accept(conn, message);
|
||||
else
|
||||
LogManager
|
||||
.info("[ProtocolAPI] Unhandled PubSub packet received id: " + message.uType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int messagesCount() {
|
||||
return PubSubUnion.names.length;
|
||||
}
|
||||
|
||||
public int createMessage(FlatBufferBuilder fbb, byte messageType, int messageOffset) {
|
||||
int[] data = new int[1];
|
||||
|
||||
data[0] = PubSubHeader.createPubSubHeader(fbb, messageType, messageOffset);
|
||||
|
||||
int messages = MessageBundle.createPubSubMsgsVector(fbb, data);
|
||||
|
||||
MessageBundle.startMessageBundle(fbb);
|
||||
MessageBundle.addPubSubMsgs(fbb, messages);
|
||||
return MessageBundle.endMessageBundle(fbb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import dev.slimevr.vr.processor.HumanPoseProcessor;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
import solarxr_protocol.rpc.SkeletonConfigResponse;
|
||||
import solarxr_protocol.rpc.SkeletonPart;
|
||||
|
||||
|
||||
public class RPCBuilder {
|
||||
|
||||
public static int createSkeletonConfig(
|
||||
FlatBufferBuilder fbb,
|
||||
HumanPoseProcessor humanPoseProcessor
|
||||
) {
|
||||
int[] partsOffsets = new int[SkeletonConfigOffsets.values().length];
|
||||
|
||||
for (int index = 0; index < SkeletonConfigOffsets.values().length; index++) {
|
||||
SkeletonConfigOffsets val = SkeletonConfigOffsets.values[index];
|
||||
int part = SkeletonPart
|
||||
.createSkeletonPart(fbb, val.id, humanPoseProcessor.getSkeletonConfig(val));
|
||||
partsOffsets[index] = part;
|
||||
}
|
||||
|
||||
int parts = SkeletonConfigResponse.createSkeletonPartsVector(fbb, partsOffsets);
|
||||
return SkeletonConfigResponse.createSkeletonConfigResponse(fbb, parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,808 @@
|
||||
package dev.slimevr.protocol;
|
||||
|
||||
import com.fazecast.jSerialComm.SerialPort;
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import com.jme3.math.Quaternion;
|
||||
import dev.slimevr.autobone.AutoBone.Epoch;
|
||||
import dev.slimevr.autobone.AutoBoneListener;
|
||||
import dev.slimevr.autobone.AutoBoneProcessType;
|
||||
import dev.slimevr.config.FiltersConfig;
|
||||
import dev.slimevr.config.OverlayConfig;
|
||||
import dev.slimevr.filtering.TrackerFilters;
|
||||
import dev.slimevr.platform.windows.WindowsNamedPipeBridge;
|
||||
import dev.slimevr.poserecorder.PoseFrames;
|
||||
import dev.slimevr.serial.SerialListener;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigToggles;
|
||||
import dev.slimevr.vr.processor.skeleton.SkeletonConfigValues;
|
||||
import dev.slimevr.vr.trackers.IMUTracker;
|
||||
import dev.slimevr.vr.trackers.Tracker;
|
||||
import dev.slimevr.vr.trackers.TrackerPosition;
|
||||
import dev.slimevr.vr.trackers.TrackerRole;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
import solarxr_protocol.MessageBundle;
|
||||
import solarxr_protocol.datatypes.TransactionId;
|
||||
import solarxr_protocol.rpc.*;
|
||||
import solarxr_protocol.rpc.settings.ModelRatios;
|
||||
import solarxr_protocol.rpc.settings.ModelSettings;
|
||||
import solarxr_protocol.rpc.settings.ModelToggles;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
|
||||
public class RPCHandler extends ProtocolHandler<RpcMessageHeader>
|
||||
implements SerialListener, AutoBoneListener {
|
||||
|
||||
private final ProtocolAPI api;
|
||||
|
||||
private long currTransactionId = 0;
|
||||
|
||||
public RPCHandler(ProtocolAPI api) {
|
||||
super();
|
||||
this.api = api;
|
||||
|
||||
registerPacketListener(RpcMessage.ResetRequest, this::onResetRequest);
|
||||
registerPacketListener(RpcMessage.AssignTrackerRequest, this::onAssignTrackerRequest);
|
||||
registerPacketListener(RpcMessage.SettingsRequest, this::onSettingsRequest);
|
||||
registerPacketListener(RpcMessage.ChangeSettingsRequest, this::onChangeSettingsRequest);
|
||||
|
||||
registerPacketListener(RpcMessage.RecordBVHRequest, this::onRecordBVHRequest);
|
||||
|
||||
registerPacketListener(RpcMessage.SkeletonResetAllRequest, this::onSkeletonResetAllRequest);
|
||||
registerPacketListener(RpcMessage.SkeletonConfigRequest, this::onSkeletonConfigRequest);
|
||||
registerPacketListener(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
this::onChangeSkeletonConfigRequest
|
||||
);
|
||||
|
||||
registerPacketListener(RpcMessage.SetWifiRequest, this::onSetWifiRequest);
|
||||
registerPacketListener(
|
||||
RpcMessage.SerialTrackerRebootRequest,
|
||||
this::SerialTrackerRebootRequest
|
||||
);
|
||||
registerPacketListener(
|
||||
RpcMessage.SerialTrackerGetInfoRequest,
|
||||
this::SerialTrackerGetInfoRequest
|
||||
);
|
||||
registerPacketListener(
|
||||
RpcMessage.SerialTrackerFactoryResetRequest,
|
||||
this::SerialTrackerFactoryResetRequest
|
||||
);
|
||||
registerPacketListener(RpcMessage.OpenSerialRequest, this::onOpenSerialRequest);
|
||||
registerPacketListener(RpcMessage.CloseSerialRequest, this::onCloseSerialRequest);
|
||||
|
||||
registerPacketListener(RpcMessage.AutoBoneProcessRequest, this::onAutoBoneProcessRequest);
|
||||
|
||||
registerPacketListener(
|
||||
RpcMessage.OverlayDisplayModeChangeRequest,
|
||||
this::onOverlayDisplayModeChangeRequest
|
||||
);
|
||||
registerPacketListener(
|
||||
RpcMessage.OverlayDisplayModeRequest,
|
||||
this::onOverlayDisplayModeRequest
|
||||
);
|
||||
|
||||
this.api.server.getSerialHandler().addListener(this);
|
||||
this.api.server.getAutoBoneHandler().addListener(this);
|
||||
}
|
||||
|
||||
private void onOverlayDisplayModeRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
OverlayConfig config = this.api.server.getConfigManager().getVrConfig().getOverlay();
|
||||
int response = OverlayDisplayModeResponse
|
||||
.createOverlayDisplayModeResponse(fbb, config.isVisible(), config.isMirrored());
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.OverlayDisplayModeResponse, response);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
private void onOverlayDisplayModeChangeRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
OverlayDisplayModeChangeRequest req = (OverlayDisplayModeChangeRequest) messageHeader
|
||||
.message(new OverlayDisplayModeChangeRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
OverlayConfig config = this.api.server.getConfigManager().getVrConfig().getOverlay();
|
||||
config.setMirrored(req.isMirrored());
|
||||
config.setVisible(req.isVisible());
|
||||
|
||||
this.api.server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
public void onSetWifiRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
SetWifiRequest req = (SetWifiRequest) messageHeader.message(new SetWifiRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
if (
|
||||
req.password() == null
|
||||
|| req.ssid() == null
|
||||
|| !this.api.server.getSerialHandler().isConnected()
|
||||
)
|
||||
return;
|
||||
this.api.server.getSerialHandler().setWifi(req.ssid(), req.password());
|
||||
}
|
||||
|
||||
public void onOpenSerialRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
OpenSerialRequest req = (OpenSerialRequest) messageHeader.message(new OpenSerialRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
conn.getContext().setUseSerial(true);
|
||||
|
||||
this.api.server.getSerialHandler().openSerial();
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, !this.api.server.getSerialHandler().isConnected());
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onCloseSerialRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
CloseSerialRequest req = (CloseSerialRequest) messageHeader
|
||||
.message(new CloseSerialRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
conn.getContext().setUseSerial(false);
|
||||
|
||||
this.api.server.getSerialHandler().closeSerial();
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, !this.api.server.getSerialHandler().isConnected());
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onSkeletonResetAllRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
SkeletonResetAllRequest req = (SkeletonResetAllRequest) messageHeader
|
||||
.message(new SkeletonResetAllRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
this.api.server.humanPoseProcessor.getSkeletonConfig().resetConfigs();
|
||||
this.api.server.getConfigManager().saveConfig();
|
||||
|
||||
// might not be a good idea maybe let the client ask again
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(300);
|
||||
int config = RPCBuilder.createSkeletonConfig(fbb, this.api.server.humanPoseProcessor);
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.SkeletonConfigResponse, config);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onSkeletonConfigRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
SkeletonConfigRequest req = (SkeletonConfigRequest) messageHeader
|
||||
.message(new SkeletonConfigRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(300);
|
||||
int config = RPCBuilder.createSkeletonConfig(fbb, this.api.server.humanPoseProcessor);
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.SkeletonConfigResponse, config);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onChangeSkeletonConfigRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
ChangeSkeletonConfigRequest req = (ChangeSkeletonConfigRequest) messageHeader
|
||||
.message(new ChangeSkeletonConfigRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
SkeletonConfigOffsets joint = SkeletonConfigOffsets.getById(req.bone());
|
||||
|
||||
this.api.server.humanPoseProcessor.setSkeletonConfig(joint, req.value());
|
||||
this.api.server.humanPoseProcessor.getSkeletonConfig().save();
|
||||
this.api.server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
public void onRecordBVHRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
RecordBVHRequest req = (RecordBVHRequest) messageHeader.message(new RecordBVHRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
if (req.stop()) {
|
||||
if (this.api.server.getBvhRecorder().isRecording())
|
||||
this.api.server.getBvhRecorder().endRecording();
|
||||
} else {
|
||||
if (!this.api.server.getBvhRecorder().isRecording())
|
||||
this.api.server.getBvhRecorder().startRecording();
|
||||
}
|
||||
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(40);
|
||||
int status = RecordBVHStatus
|
||||
.createRecordBVHStatus(fbb, this.api.server.getBvhRecorder().isRecording());
|
||||
int outbound = this.createRPCMessage(fbb, RpcMessage.RecordBVHStatus, status);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onResetRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
ResetRequest req = (ResetRequest) messageHeader.message(new ResetRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
if (req.resetType() == ResetType.Quick)
|
||||
this.api.server.resetTrackersYaw();
|
||||
if (req.resetType() == ResetType.Full)
|
||||
this.api.server.resetTrackers();
|
||||
LogManager.severe("[WebSocketAPI] Reset performed");
|
||||
}
|
||||
|
||||
public void onAssignTrackerRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
AssignTrackerRequest req = (AssignTrackerRequest) messageHeader
|
||||
.message(new AssignTrackerRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
Tracker tracker = this.api.server.getTrackerById(req.trackerId().unpack());
|
||||
if (tracker == null)
|
||||
return;
|
||||
tracker = tracker.get();
|
||||
|
||||
TrackerPosition pos = TrackerPosition.getByBodyPart(req.bodyPosition()).orElse(null);
|
||||
tracker.setBodyPosition(pos);
|
||||
|
||||
if (req.mountingRotation() != null) {
|
||||
if (tracker instanceof IMUTracker imu) {
|
||||
imu
|
||||
.setMountingRotation(
|
||||
new Quaternion(
|
||||
req.mountingRotation().x(),
|
||||
req.mountingRotation().y(),
|
||||
req.mountingRotation().z(),
|
||||
req.mountingRotation().w()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (req.displayName() != null) {
|
||||
if (tracker instanceof IMUTracker imu) {
|
||||
imu.setCustomName(req.displayName());
|
||||
}
|
||||
}
|
||||
|
||||
this.api.server.trackerUpdated(tracker);
|
||||
}
|
||||
|
||||
public void onSettingsRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
WindowsNamedPipeBridge bridge = this.api.server.getVRBridge(WindowsNamedPipeBridge.class);
|
||||
|
||||
int steamvrTrackerSettings = SteamVRTrackersSetting
|
||||
.createSteamVRTrackersSetting(
|
||||
fbb,
|
||||
bridge.getShareSetting(TrackerRole.WAIST),
|
||||
bridge.getShareSetting(TrackerRole.CHEST),
|
||||
bridge.getShareSetting(TrackerRole.LEFT_FOOT)
|
||||
&& bridge.getShareSetting(TrackerRole.RIGHT_FOOT),
|
||||
bridge.getShareSetting(TrackerRole.LEFT_KNEE)
|
||||
&& bridge.getShareSetting(TrackerRole.RIGHT_KNEE),
|
||||
bridge.getShareSetting(TrackerRole.LEFT_ELBOW)
|
||||
&& bridge.getShareSetting(TrackerRole.RIGHT_ELBOW)
|
||||
);
|
||||
|
||||
FiltersConfig filtersConfig = this.api.server
|
||||
.getConfigManager()
|
||||
.getVrConfig()
|
||||
.getFilters();
|
||||
|
||||
int filterSettings = FilteringSettings
|
||||
.createFilteringSettings(
|
||||
fbb,
|
||||
TrackerFilters.getByConfigkey(filtersConfig.getType()).id,
|
||||
filtersConfig.getAmount()
|
||||
);
|
||||
|
||||
int modelSettings;
|
||||
{
|
||||
var config = this.api.server.humanPoseProcessor.getSkeletonConfig();
|
||||
int togglesOffset = ModelToggles
|
||||
.createModelToggles(
|
||||
fbb,
|
||||
config.getToggle(SkeletonConfigToggles.EXTENDED_SPINE_MODEL),
|
||||
config.getToggle(SkeletonConfigToggles.EXTENDED_PELVIS_MODEL),
|
||||
config.getToggle(SkeletonConfigToggles.EXTENDED_KNEE_MODEL),
|
||||
config.getToggle(SkeletonConfigToggles.FORCE_ARMS_FROM_HMD),
|
||||
config.getToggle(SkeletonConfigToggles.SKATING_CORRECTION),
|
||||
config.getToggle(SkeletonConfigToggles.FLOOR_CLIP)
|
||||
);
|
||||
int ratiosOffset = ModelRatios
|
||||
.createModelRatios(
|
||||
fbb,
|
||||
config.getValue(SkeletonConfigValues.WAIST_FROM_CHEST_HIP_AVERAGING),
|
||||
config.getValue(SkeletonConfigValues.WAIST_FROM_CHEST_LEGS_AVERAGING),
|
||||
config.getValue(SkeletonConfigValues.HIP_FROM_CHEST_LEGS_AVERAGING),
|
||||
config.getValue(SkeletonConfigValues.HIP_FROM_WAIST_LEGS_AVERAGING),
|
||||
config.getValue(SkeletonConfigValues.HIP_LEGS_AVERAGING),
|
||||
config.getValue(SkeletonConfigValues.KNEE_TRACKER_ANKLE_AVERAGING)
|
||||
);
|
||||
modelSettings = ModelSettings.createModelSettings(fbb, togglesOffset, ratiosOffset);
|
||||
}
|
||||
|
||||
int settings = SettingsResponse
|
||||
.createSettingsResponse(fbb, steamvrTrackerSettings, filterSettings, modelSettings);
|
||||
int outbound = createRPCMessage(fbb, RpcMessage.SettingsResponse, settings);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
}
|
||||
|
||||
public void onChangeSettingsRequest(GenericConnection conn, RpcMessageHeader messageHeader) {
|
||||
|
||||
ChangeSettingsRequest req = (ChangeSettingsRequest) messageHeader
|
||||
.message(new ChangeSettingsRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
if (req.steamVrTrackers() != null) {
|
||||
WindowsNamedPipeBridge bridge = this.api.server
|
||||
.getVRBridge(WindowsNamedPipeBridge.class);
|
||||
bridge.changeShareSettings(TrackerRole.WAIST, req.steamVrTrackers().waist());
|
||||
bridge.changeShareSettings(TrackerRole.CHEST, req.steamVrTrackers().chest());
|
||||
bridge.changeShareSettings(TrackerRole.LEFT_FOOT, req.steamVrTrackers().legs());
|
||||
bridge.changeShareSettings(TrackerRole.RIGHT_FOOT, req.steamVrTrackers().legs());
|
||||
bridge.changeShareSettings(TrackerRole.LEFT_KNEE, req.steamVrTrackers().knees());
|
||||
bridge.changeShareSettings(TrackerRole.RIGHT_KNEE, req.steamVrTrackers().knees());
|
||||
bridge.changeShareSettings(TrackerRole.LEFT_ELBOW, req.steamVrTrackers().elbows());
|
||||
bridge.changeShareSettings(TrackerRole.RIGHT_ELBOW, req.steamVrTrackers().elbows());
|
||||
}
|
||||
|
||||
if (req.filtering() != null) {
|
||||
TrackerFilters type = TrackerFilters.fromId(req.filtering().type());
|
||||
if (type != null) {
|
||||
FiltersConfig filtersConfig = this.api.server
|
||||
.getConfigManager()
|
||||
.getVrConfig()
|
||||
.getFilters();
|
||||
filtersConfig.setType(type.configKey);
|
||||
filtersConfig.setAmount(req.filtering().amount());
|
||||
|
||||
this.api.server.getConfigManager().saveConfig();
|
||||
|
||||
filtersConfig.updateTrackersFilters();
|
||||
}
|
||||
}
|
||||
|
||||
var modelSettings = req.modelSettings();
|
||||
if (modelSettings != null) {
|
||||
var cfg = this.api.server.humanPoseProcessor.getSkeletonConfig();
|
||||
var toggles = modelSettings.toggles();
|
||||
var ratios = modelSettings.ratios();
|
||||
|
||||
if (toggles != null) {
|
||||
// Note: toggles.has____ returns the same as toggles._____ this
|
||||
// seems like a bug
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_SPINE_MODEL,
|
||||
toggles.extendedSpine()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_PELVIS_MODEL,
|
||||
toggles.extendedPelvis()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_KNEE_MODEL,
|
||||
toggles.extendedKnee()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.FORCE_ARMS_FROM_HMD,
|
||||
toggles.forceArmsFromHmd()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_SPINE_MODEL,
|
||||
toggles.extendedSpine()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_PELVIS_MODEL,
|
||||
toggles.extendedPelvis()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.EXTENDED_KNEE_MODEL,
|
||||
toggles.extendedKnee()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.FORCE_ARMS_FROM_HMD,
|
||||
toggles.forceArmsFromHmd()
|
||||
);
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.FLOOR_CLIP,
|
||||
toggles.floorClip()
|
||||
);
|
||||
|
||||
cfg
|
||||
.setToggle(
|
||||
SkeletonConfigToggles.SKATING_CORRECTION,
|
||||
toggles.skatingCorrection()
|
||||
);
|
||||
}
|
||||
|
||||
if (ratios != null) {
|
||||
if (ratios.hasImputeWaistFromChestHip()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.WAIST_FROM_CHEST_HIP_AVERAGING,
|
||||
ratios.imputeWaistFromChestHip()
|
||||
);
|
||||
}
|
||||
if (ratios.hasImputeWaistFromChestLegs()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.WAIST_FROM_CHEST_LEGS_AVERAGING,
|
||||
ratios.imputeWaistFromChestLegs()
|
||||
);
|
||||
}
|
||||
if (ratios.hasImputeHipFromChestLegs()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.HIP_FROM_CHEST_LEGS_AVERAGING,
|
||||
ratios.imputeHipFromChestLegs()
|
||||
);
|
||||
}
|
||||
if (ratios.hasImputeHipFromWaistLegs()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.HIP_FROM_WAIST_LEGS_AVERAGING,
|
||||
ratios.imputeHipFromWaistLegs()
|
||||
);
|
||||
}
|
||||
if (ratios.hasInterpHipLegs()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.HIP_LEGS_AVERAGING,
|
||||
ratios.interpHipLegs()
|
||||
);
|
||||
}
|
||||
if (ratios.hasInterpKneeTrackerAnkle()) {
|
||||
cfg
|
||||
.setValue(
|
||||
SkeletonConfigValues.KNEE_TRACKER_ANKLE_AVERAGING,
|
||||
ratios.interpKneeTrackerAnkle()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cfg.save();
|
||||
this.api.server.getConfigManager().saveConfig();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(GenericConnection conn, RpcMessageHeader message) {
|
||||
BiConsumer<GenericConnection, RpcMessageHeader> consumer = this.handlers[message
|
||||
.messageType()];
|
||||
if (consumer != null)
|
||||
consumer.accept(conn, message);
|
||||
else
|
||||
LogManager
|
||||
.info("[ProtocolAPI] Unhandled RPC packet received id: " + message.messageType());
|
||||
}
|
||||
|
||||
public int createRPCMessage(FlatBufferBuilder fbb, byte messageType, int messageOffset) {
|
||||
int[] data = new int[1];
|
||||
|
||||
RpcMessageHeader.startRpcMessageHeader(fbb);
|
||||
RpcMessageHeader.addMessage(fbb, messageOffset);
|
||||
RpcMessageHeader.addMessageType(fbb, messageType);
|
||||
RpcMessageHeader.addTxId(fbb, TransactionId.createTransactionId(fbb, currTransactionId++));
|
||||
data[0] = RpcMessageHeader.endRpcMessageHeader(fbb);
|
||||
|
||||
int messages = MessageBundle.createRpcMsgsVector(fbb, data);
|
||||
|
||||
MessageBundle.startMessageBundle(fbb);
|
||||
MessageBundle.addRpcMsgs(fbb, messages);
|
||||
return MessageBundle.endMessageBundle(fbb);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int messagesCount() {
|
||||
return RpcMessage.names.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSerialConnected(SerialPort port) {
|
||||
|
||||
this.api
|
||||
.getAPIServers()
|
||||
.forEach(
|
||||
(server) -> server
|
||||
.getAPIConnections()
|
||||
.filter(conn -> conn.getContext().useSerial())
|
||||
.forEach((conn) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, false);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn.send(fbb.dataBuffer());
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public void SerialTrackerRebootRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
SerialTrackerRebootRequest req = (SerialTrackerRebootRequest) messageHeader
|
||||
.message(new SerialTrackerRebootRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
this.api.server.getSerialHandler().rebootRequest();
|
||||
|
||||
this.api.getAPIServers().forEach((server) -> {
|
||||
server
|
||||
.getAPIConnections()
|
||||
.filter(conn2 -> conn2.getContext().useSerial())
|
||||
.forEach((conn2) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, false);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn2.send(fbb.dataBuffer());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void SerialTrackerGetInfoRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
SerialTrackerGetInfoRequest req = (SerialTrackerGetInfoRequest) messageHeader
|
||||
.message(new SerialTrackerGetInfoRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
this.api.server.getSerialHandler().infoRequest();
|
||||
|
||||
this.api.getAPIServers().forEach((server) -> {
|
||||
server
|
||||
.getAPIConnections()
|
||||
.filter(conn2 -> conn2.getContext().useSerial())
|
||||
.forEach((conn2) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, false);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn2.send(fbb.dataBuffer());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public void SerialTrackerFactoryResetRequest(
|
||||
GenericConnection conn,
|
||||
RpcMessageHeader messageHeader
|
||||
) {
|
||||
SerialTrackerFactoryResetRequest req = (SerialTrackerFactoryResetRequest) messageHeader
|
||||
.message(new SerialTrackerFactoryResetRequest());
|
||||
if (req == null)
|
||||
return;
|
||||
|
||||
this.api.server.getSerialHandler().factoryResetRequest();
|
||||
|
||||
this.api.getAPIServers().forEach((server) -> {
|
||||
server
|
||||
.getAPIConnections()
|
||||
.filter(conn2 -> conn2.getContext().useSerial())
|
||||
.forEach((conn2) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, false);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn2.send(fbb.dataBuffer());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSerialDisconnected() {
|
||||
this.api
|
||||
.getAPIServers()
|
||||
.forEach(
|
||||
(server) -> server
|
||||
.getAPIConnections()
|
||||
.filter(conn -> conn.getContext().useSerial())
|
||||
.forEach((conn) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addClosed(fbb, true);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
conn.send(fbb.dataBuffer());
|
||||
conn.getContext().setUseSerial(false);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSerialLog(String str) {
|
||||
this.api
|
||||
.getAPIServers()
|
||||
.forEach(
|
||||
(server) -> server
|
||||
.getAPIConnections()
|
||||
.filter(conn -> conn.getContext().useSerial())
|
||||
.forEach((conn) -> {
|
||||
FlatBufferBuilder fbb = new FlatBufferBuilder(32);
|
||||
|
||||
int logOffset = fbb.createString(str);
|
||||
|
||||
SerialUpdateResponse.startSerialUpdateResponse(fbb);
|
||||
SerialUpdateResponse.addLog(fbb, logOffset);
|
||||
int update = SerialUpdateResponse.endSerialUpdateResponse(fbb);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn.send(fbb.dataBuffer());
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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<SkeletonConfigOffsets, Float> 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.getMean(),
|
||||
skeletonPartsOffset
|
||||
);
|
||||
int outbound = this
|
||||
.createRPCMessage(fbb, RpcMessage.AutoBoneEpochResponse, update);
|
||||
fbb.finish(outbound);
|
||||
|
||||
conn.send(fbb.dataBuffer());
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onAutoBoneEnd(EnumMap<SkeletonConfigOffsets, Float> configValues) {
|
||||
// Do nothing, the last epoch from "onAutoBoneEpoch" should be all
|
||||
// that's needed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package dev.slimevr.serial;
|
||||
|
||||
import com.fazecast.jSerialComm.SerialPort;
|
||||
import com.fazecast.jSerialComm.SerialPortEvent;
|
||||
import com.fazecast.jSerialComm.SerialPortMessageListener;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import static java.util.concurrent.TimeUnit.*;
|
||||
|
||||
|
||||
public class SerialHandler implements SerialPortMessageListener {
|
||||
|
||||
private final List<SerialListener> listeners = new CopyOnWriteArrayList<>();
|
||||
private SerialPort trackerPort = null;
|
||||
|
||||
public void addListener(SerialListener channel) {
|
||||
this.listeners.add(channel);
|
||||
}
|
||||
|
||||
public void removeListener(SerialListener l) {
|
||||
listeners.removeIf(listener -> l == listener);
|
||||
}
|
||||
|
||||
public boolean openSerial() {
|
||||
if (this.isConnected()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
SerialPort[] ports = SerialPort.getCommPorts();
|
||||
for (SerialPort port : ports) {
|
||||
if (
|
||||
port.getDescriptivePortName().toLowerCase().contains("ch340")
|
||||
|| port.getDescriptivePortName().toLowerCase().contains("cp21")
|
||||
|| port.getDescriptivePortName().toLowerCase().contains("ch910")
|
||||
|| (port.getDescriptivePortName().toLowerCase().contains("usb")
|
||||
&& port.getDescriptivePortName().toLowerCase().contains("seri"))
|
||||
) {
|
||||
trackerPort = port;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (trackerPort == null) {
|
||||
return false;
|
||||
}
|
||||
trackerPort.setBaudRate(115200);
|
||||
trackerPort.clearRTS();
|
||||
trackerPort.clearDTR();
|
||||
if (!trackerPort.openPort()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
trackerPort.addDataListener(this);
|
||||
this.listeners.forEach((listener) -> listener.onSerialConnected(trackerPort));
|
||||
return true;
|
||||
}
|
||||
|
||||
public void rebootRequest() {
|
||||
this.writeSerial("REBOOT");
|
||||
}
|
||||
|
||||
public void factoryResetRequest() {
|
||||
this.writeSerial("FRST");
|
||||
}
|
||||
|
||||
public void infoRequest() {
|
||||
this.writeSerial("GET INFO");
|
||||
}
|
||||
|
||||
public void closeSerial() {
|
||||
try {
|
||||
if (trackerPort != null)
|
||||
trackerPort.closePort();
|
||||
this.listeners.forEach(SerialListener::onSerialDisconnected);
|
||||
System.out.println("Port closed okay");
|
||||
trackerPort = null;
|
||||
} catch (Exception e) {
|
||||
System.out.println("Error closing port: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeSerial(String serialText) {
|
||||
if (trackerPort == null)
|
||||
return;
|
||||
OutputStream os = trackerPort.getOutputStream();
|
||||
OutputStreamWriter writer = new OutputStreamWriter(os);
|
||||
try {
|
||||
writer.append(serialText + "\n");
|
||||
writer.flush();
|
||||
this.addLog("-> " + serialText + "\n");
|
||||
} catch (IOException e) {
|
||||
addLog(e + "\n");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void setWifi(String ssid, String passwd) {
|
||||
if (trackerPort == null)
|
||||
return;
|
||||
OutputStream os = trackerPort.getOutputStream();
|
||||
OutputStreamWriter writer = new OutputStreamWriter(os);
|
||||
try {
|
||||
writer.append("SET WIFI \"").append(ssid).append("\" \"").append(passwd).append("\"\n");
|
||||
writer.flush();
|
||||
this.addLog("-> SET WIFI \"" + ssid + "\" \"" + passwd.replaceAll(".", "*") + "\"\n");
|
||||
} catch (IOException e) {
|
||||
addLog(e + "\n");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void addLog(String str) {
|
||||
this.listeners.forEach(listener -> listener.onSerialLog(str));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getListeningEvents() {
|
||||
return SerialPort.LISTENING_EVENT_PORT_DISCONNECTED
|
||||
| SerialPort.LISTENING_EVENT_DATA_RECEIVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialEvent(SerialPortEvent event) {
|
||||
if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_RECEIVED) {
|
||||
byte[] newData = event.getReceivedData();
|
||||
String s = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(newData)).toString();
|
||||
this.addLog(s);
|
||||
} else if (event.getEventType() == SerialPort.LISTENING_EVENT_PORT_DISCONNECTED) {
|
||||
this.closeSerial();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return this.trackerPort != null && this.trackerPort.isOpen();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getMessageDelimiter() {
|
||||
return new byte[] { (byte) 0x0A };
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delimiterIndicatesEndOfMessage() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 430 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user