mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-25 03:21:21 -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
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.math;
|
||||
|
||||
/**
|
||||
* Temporary variables assigned to each thread. Engine classes may access these
|
||||
* temp variables with TempVars.get(), all retrieved TempVars instances must be
|
||||
* returned via TempVars.release(). This returns an available instance of the
|
||||
* TempVar class ensuring this particular instance is never used elsewhere in
|
||||
* the mean time.
|
||||
*/
|
||||
public class TempVars {
|
||||
|
||||
/**
|
||||
* Allow X instances of TempVars in a single thread.
|
||||
*/
|
||||
private static final int STACK_SIZE = 5;
|
||||
|
||||
/**
|
||||
* <code>TempVarsStack</code> contains a stack of TempVars. Every time
|
||||
* TempVars.get() is called, a new entry is added to the stack, and the
|
||||
* index incremented. When TempVars.release() is called, the entry is
|
||||
* checked against the current instance and then the index is decremented.
|
||||
*/
|
||||
private static class TempVarsStack {
|
||||
|
||||
int index = 0;
|
||||
TempVars[] tempVars = new TempVars[STACK_SIZE];
|
||||
}
|
||||
|
||||
/**
|
||||
* ThreadLocal to store a TempVarsStack for each thread. This ensures each
|
||||
* thread has a single TempVarsStack that is used only in method calls in
|
||||
* that thread.
|
||||
*/
|
||||
private static final ThreadLocal<TempVarsStack> varsLocal = new ThreadLocal<TempVarsStack>() {
|
||||
|
||||
@Override
|
||||
public TempVarsStack initialValue() {
|
||||
return new TempVarsStack();
|
||||
}
|
||||
};
|
||||
/**
|
||||
* This instance of TempVars has been retrieved but not released yet.
|
||||
*/
|
||||
private boolean isUsed = false;
|
||||
|
||||
private TempVars() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire an instance of the TempVar class. You have to release the
|
||||
* instance after use by calling the release() method. If more than
|
||||
* STACK_SIZE (currently 5) instances are requested in a single thread then
|
||||
* an ArrayIndexOutOfBoundsException will be thrown.
|
||||
*
|
||||
* @return A TempVar instance
|
||||
*/
|
||||
public static TempVars get() {
|
||||
TempVarsStack stack = varsLocal.get();
|
||||
|
||||
TempVars instance = stack.tempVars[stack.index];
|
||||
|
||||
if (instance == null) {
|
||||
// Create new
|
||||
instance = new TempVars();
|
||||
|
||||
// Put it in there
|
||||
stack.tempVars[stack.index] = instance;
|
||||
}
|
||||
|
||||
stack.index++;
|
||||
|
||||
instance.isUsed = true;
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases this instance of TempVars. Once released, the contents of the
|
||||
* TempVars are undefined. The TempVars must be released in the opposite
|
||||
* order that they are retrieved, e.g. Acquiring vars1, then acquiring
|
||||
* vars2, vars2 MUST be released first otherwise an exception will be
|
||||
* thrown.
|
||||
*/
|
||||
public void release() {
|
||||
if (!isUsed) {
|
||||
throw new IllegalStateException("This instance of TempVars was already released!");
|
||||
}
|
||||
|
||||
isUsed = false;
|
||||
|
||||
TempVarsStack stack = varsLocal.get();
|
||||
|
||||
// Return it to the stack
|
||||
stack.index--;
|
||||
|
||||
// Check if it is actually there
|
||||
if (stack.tempVars[stack.index] != this) {
|
||||
throw new IllegalStateException(
|
||||
"An instance of TempVars has not been released in a called method!"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* General vectors.
|
||||
*/
|
||||
public final Vector3f vect1 = new Vector3f();
|
||||
public final Vector3f vect2 = new Vector3f();
|
||||
public final Vector3f vect3 = new Vector3f();
|
||||
/**
|
||||
* General matrices.
|
||||
*/
|
||||
public final Matrix4f tempMat4 = new Matrix4f();
|
||||
|
||||
public final float[] matrixWrite = new float[16];
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.math;
|
||||
|
||||
/**
|
||||
* Started Date: Jul 16, 2004<br>
|
||||
* <br>
|
||||
* Represents a translation, rotation and scale in one object.
|
||||
*
|
||||
* @author Jack Lindamood
|
||||
* @author Joshua Slack
|
||||
*/
|
||||
public final class Transform implements Cloneable, java.io.Serializable {
|
||||
|
||||
static final long serialVersionUID = 1;
|
||||
|
||||
public static final Transform IDENTITY = new Transform();
|
||||
|
||||
private Quaternion rot = new Quaternion();
|
||||
private Vector3f translation = new Vector3f();
|
||||
private Vector3f scale = new Vector3f(1, 1, 1);
|
||||
|
||||
public Transform(Vector3f translation, Quaternion rot) {
|
||||
this.translation.set(translation);
|
||||
this.rot.set(rot);
|
||||
}
|
||||
|
||||
public Transform(Vector3f translation, Quaternion rot, Vector3f scale) {
|
||||
this(translation, rot);
|
||||
this.scale.set(scale);
|
||||
}
|
||||
|
||||
public Transform(Vector3f translation) {
|
||||
this(translation, Quaternion.IDENTITY);
|
||||
}
|
||||
|
||||
public Transform(Quaternion rot) {
|
||||
this(Vector3f.ZERO, rot);
|
||||
}
|
||||
|
||||
public Transform() {
|
||||
this(Vector3f.ZERO, Quaternion.IDENTITY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this rotation to the given Quaternion value.
|
||||
*
|
||||
* @param rot The new rotation for this matrix.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setRotation(Quaternion rot) {
|
||||
this.rot.set(rot);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this translation to the given value.
|
||||
*
|
||||
* @param trans The new translation for this matrix.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setTranslation(Vector3f trans) {
|
||||
this.translation.set(trans);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the translation vector in this matrix.
|
||||
*
|
||||
* @return translation vector.
|
||||
*/
|
||||
public Vector3f getTranslation() {
|
||||
return translation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this scale to the given value.
|
||||
*
|
||||
* @param scale The new scale for this matrix.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setScale(Vector3f scale) {
|
||||
this.scale.set(scale);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this scale to the given value.
|
||||
*
|
||||
* @param scale The new scale for this matrix.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setScale(float scale) {
|
||||
this.scale.set(scale, scale, scale);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the scale vector in this matrix.
|
||||
*
|
||||
* @return scale vector.
|
||||
*/
|
||||
public Vector3f getScale() {
|
||||
return scale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores this translation value into the given vector3f. If trans is null,
|
||||
* a new vector3f is created to hold the value. The value, once stored, is
|
||||
* returned.
|
||||
*
|
||||
* @param trans The store location for this matrix's translation.
|
||||
* @return The value of this matrix's translation.
|
||||
*/
|
||||
public Vector3f getTranslation(Vector3f trans) {
|
||||
if (trans == null)
|
||||
trans = new Vector3f();
|
||||
trans.set(this.translation);
|
||||
return trans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores this rotation value into the given Quaternion. If quat is null, a
|
||||
* new Quaternion is created to hold the value. The value, once stored, is
|
||||
* returned.
|
||||
*
|
||||
* @param quat The store location for this matrix's rotation.
|
||||
* @return The value of this matrix's rotation.
|
||||
*/
|
||||
public Quaternion getRotation(Quaternion quat) {
|
||||
if (quat == null)
|
||||
quat = new Quaternion();
|
||||
quat.set(rot);
|
||||
return quat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the rotation quaternion in this matrix.
|
||||
*
|
||||
* @return rotation quaternion.
|
||||
*/
|
||||
public Quaternion getRotation() {
|
||||
return rot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores this scale value into the given vector3f. If scale is null, a new
|
||||
* vector3f is created to hold the value. The value, once stored, is
|
||||
* returned.
|
||||
*
|
||||
* @param scale The store location for this matrix's scale.
|
||||
* @return The value of this matrix's scale.
|
||||
*/
|
||||
public Vector3f getScale(Vector3f scale) {
|
||||
if (scale == null)
|
||||
scale = new Vector3f();
|
||||
scale.set(this.scale);
|
||||
return scale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this matrix to the interpolation between the first matrix and the
|
||||
* second by delta amount.
|
||||
*
|
||||
* @param t1 The begining transform.
|
||||
* @param t2 The ending transform.
|
||||
* @param delta An amount between 0 and 1 representing how far to
|
||||
* interpolate from t1 to t2.
|
||||
*/
|
||||
public void interpolateTransforms(Transform t1, Transform t2, float delta) {
|
||||
this.rot.slerp(t1.rot, t2.rot, delta);
|
||||
this.translation.interpolate(t1.translation, t2.translation, delta);
|
||||
this.scale.interpolate(t1.scale, t2.scale, delta);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the values of this matrix acording to it's parent. Very similar
|
||||
* to the concept of Node/Spatial transforms.
|
||||
*
|
||||
* @param parent The parent matrix.
|
||||
* @return This matrix, after combining.
|
||||
*/
|
||||
public Transform combineWithParent(Transform parent) {
|
||||
scale.multLocal(parent.scale);
|
||||
// rot.multLocal(parent.rot);
|
||||
parent.rot.mult(rot, rot);
|
||||
|
||||
// This here, is evil code
|
||||
// parent
|
||||
// .rot
|
||||
// .multLocal(translation)
|
||||
// .multLocal(parent.scale)
|
||||
// .addLocal(parent.translation);
|
||||
|
||||
translation.multLocal(parent.scale);
|
||||
parent.rot
|
||||
.multLocal(translation)
|
||||
.addLocal(parent.translation);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link #combineWithParent(Transform)}, but assumes that rotation
|
||||
* is global, so it's not modified.
|
||||
*
|
||||
* @param parent
|
||||
* @return
|
||||
*/
|
||||
public Transform combineWithParentGlobalRotation(Transform parent) {
|
||||
scale.multLocal(parent.scale);
|
||||
translation.multLocal(parent.scale);
|
||||
|
||||
parent.rot
|
||||
.multLocal(translation)
|
||||
.addLocal(parent.translation);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this matrix's translation to the given x,y,z values.
|
||||
*
|
||||
* @param x This matrix's new x translation.
|
||||
* @param y This matrix's new y translation.
|
||||
* @param z This matrix's new z translation.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setTranslation(float x, float y, float z) {
|
||||
translation.set(x, y, z);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this matrix's scale to the given x,y,z values.
|
||||
*
|
||||
* @param x This matrix's new x scale.
|
||||
* @param y This matrix's new y scale.
|
||||
* @param z This matrix's new z scale.
|
||||
* @return this
|
||||
*/
|
||||
public Transform setScale(float x, float y, float z) {
|
||||
scale.set(x, y, z);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vector3f transformVector(final Vector3f in, Vector3f store) {
|
||||
if (store == null)
|
||||
store = new Vector3f();
|
||||
|
||||
// multiply with scale first, then rotate, finally translate (cf.
|
||||
// Eberly)
|
||||
return rot.mult(store.set(in).multLocal(scale), store).addLocal(translation);
|
||||
}
|
||||
|
||||
public Vector3f transformInverseVector(final Vector3f in, Vector3f store) {
|
||||
if (store == null)
|
||||
store = new Vector3f();
|
||||
|
||||
// The author of this code should look above and take the inverse of
|
||||
// that
|
||||
// But for some reason, they didnt ..
|
||||
// in.subtract(translation, store).divideLocal(scale);
|
||||
// rot.inverse().mult(store, store);
|
||||
|
||||
in.subtract(translation, store);
|
||||
rot.inverse().mult(store, store);
|
||||
store.divideLocal(scale);
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the identity. Equal to translation=0,0,0 scale=1,1,1 rot=0,0,0,1.
|
||||
*/
|
||||
public void loadIdentity() {
|
||||
translation.set(0, 0, 0);
|
||||
scale.set(1, 1, 1);
|
||||
rot.set(0, 0, 0, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getSimpleName()
|
||||
+ "[ "
|
||||
+ translation.x
|
||||
+ ", "
|
||||
+ translation.y
|
||||
+ ", "
|
||||
+ translation.z
|
||||
+ "]\n"
|
||||
+ "[ "
|
||||
+ rot.x
|
||||
+ ", "
|
||||
+ rot.y
|
||||
+ ", "
|
||||
+ rot.z
|
||||
+ ", "
|
||||
+ rot.w
|
||||
+ "]\n"
|
||||
+ "[ "
|
||||
+ scale.x
|
||||
+ " , "
|
||||
+ scale.y
|
||||
+ ", "
|
||||
+ scale.z
|
||||
+ "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this matrix to be equal to the given matrix.
|
||||
*
|
||||
* @param matrixQuat The matrix to be equal to.
|
||||
* @return this
|
||||
*/
|
||||
public Transform set(Transform matrixQuat) {
|
||||
this.translation.set(matrixQuat.translation);
|
||||
this.rot.set(matrixQuat.rot);
|
||||
this.scale.set(matrixQuat.scale);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((rot == null) ? 0 : rot.hashCode());
|
||||
result = prime * result + ((scale == null) ? 0 : scale.hashCode());
|
||||
result = prime * result + ((translation == null) ? 0 : translation.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Transform other = (Transform) obj;
|
||||
if (rot == null) {
|
||||
if (other.rot != null)
|
||||
return false;
|
||||
} else if (!rot.equals(other.rot))
|
||||
return false;
|
||||
if (scale == null) {
|
||||
if (other.scale != null)
|
||||
return false;
|
||||
} else if (!scale.equals(other.scale))
|
||||
return false;
|
||||
if (translation == null) {
|
||||
if (other.translation != null)
|
||||
return false;
|
||||
} else if (!translation.equals(other.translation))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transform clone() {
|
||||
try {
|
||||
Transform tq = (Transform) super.clone();
|
||||
tq.rot = rot.clone();
|
||||
tq.scale = scale.clone();
|
||||
tq.translation = translation.clone();
|
||||
return tq;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.math;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectOutput;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* <code>Vector2f</code> defines a Vector for a two float value vector.
|
||||
*
|
||||
* @author Mark Powell
|
||||
* @author Joshua Slack
|
||||
*/
|
||||
public final class Vector2f implements Cloneable, java.io.Serializable {
|
||||
|
||||
static final long serialVersionUID = 1;
|
||||
private static final Logger logger = Logger.getLogger(Vector2f.class.getName());
|
||||
|
||||
public static final Vector2f ZERO = new Vector2f(0f, 0f);
|
||||
public static final Vector2f UNIT_XY = new Vector2f(1f, 1f);
|
||||
|
||||
/**
|
||||
* the x value of the vector.
|
||||
*/
|
||||
public float x;
|
||||
/**
|
||||
* the y value of the vector.
|
||||
*/
|
||||
public float y;
|
||||
|
||||
/**
|
||||
* Creates a Vector2f with the given initial x and y values.
|
||||
*
|
||||
* @param x The x value of this Vector2f.
|
||||
* @param y The y value of this Vector2f.
|
||||
*/
|
||||
public Vector2f(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Vector2f with x and y set to 0. Equivalent to Vector2f(0,0).
|
||||
*/
|
||||
public Vector2f() {
|
||||
x = y = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Vector2f that contains the passed vector's information
|
||||
*
|
||||
* @param vector2f The vector to copy
|
||||
*/
|
||||
public Vector2f(Vector2f vector2f) {
|
||||
this.x = vector2f.x;
|
||||
this.y = vector2f.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* set the x and y values of the vector
|
||||
*
|
||||
* @param x the x value of the vector.
|
||||
* @param y the y value of the vector.
|
||||
* @return this vector
|
||||
*/
|
||||
public Vector2f set(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* set the x and y values of the vector from another vector
|
||||
*
|
||||
* @param vec the vector to copy from
|
||||
* @return this vector
|
||||
*/
|
||||
public Vector2f set(Vector2f vec) {
|
||||
this.x = vec.x;
|
||||
this.y = vec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>add</code> adds a provided vector to this vector creating a
|
||||
* resultant vector which is returned. If the provided vector is null, null
|
||||
* is returned.
|
||||
*
|
||||
* @param vec the vector to add to this.
|
||||
* @return the resultant vector.
|
||||
*/
|
||||
public Vector2f add(Vector2f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
return new Vector2f(x + vec.x, y + vec.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>addLocal</code> adds a provided vector to this vector internally,
|
||||
* and returns a handle to this vector for easy chaining of calls. If the
|
||||
* provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to add to this vector.
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f addLocal(Vector2f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x += vec.x;
|
||||
y += vec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>addLocal</code> adds the provided values to this vector internally,
|
||||
* and returns a handle to this vector for easy chaining of calls.
|
||||
*
|
||||
* @param addX value to add to x
|
||||
* @param addY value to add to y
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f addLocal(float addX, float addY) {
|
||||
x += addX;
|
||||
y += addY;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>add</code> adds this vector by <code>vec</code> and stores the
|
||||
* result in <code>result</code>.
|
||||
*
|
||||
* @param vec The vector to add.
|
||||
* @param result The vector to store the result in.
|
||||
* @return The result vector, after adding.
|
||||
*/
|
||||
public Vector2f add(Vector2f vec, Vector2f result) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
if (result == null)
|
||||
result = new Vector2f();
|
||||
result.x = x + vec.x;
|
||||
result.y = y + vec.y;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>dot</code> calculates the dot product of this vector with a
|
||||
* provided vector. If the provided vector is null, 0 is returned.
|
||||
*
|
||||
* @param vec the vector to dot with this vector.
|
||||
* @return the resultant dot product of this vector and a given vector.
|
||||
*/
|
||||
public float dot(Vector2f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, 0 returned.");
|
||||
return 0;
|
||||
}
|
||||
return x * vec.x + y * vec.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>cross</code> calculates the cross product of this vector with a
|
||||
* parameter vector v.
|
||||
*
|
||||
* @param v the vector to take the cross product of with this.
|
||||
* @return the cross product vector.
|
||||
*/
|
||||
public Vector3f cross(Vector2f v) {
|
||||
return new Vector3f(0, 0, determinant(v));
|
||||
}
|
||||
|
||||
public float determinant(Vector2f v) {
|
||||
return (x * v.y) - (y * v.x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this vector to the interpolation by changeAmnt from this to the
|
||||
* finalVec this=(1-changeAmnt)*this + changeAmnt * finalVec
|
||||
*
|
||||
* @param finalVec The final vector to interpolate towards
|
||||
* @param changeAmnt An amount between 0.0 - 1.0 representing a percentage
|
||||
* change from this towards finalVec
|
||||
*/
|
||||
public Vector2f interpolate(Vector2f finalVec, float changeAmnt) {
|
||||
this.x = (1 - changeAmnt) * this.x + changeAmnt * finalVec.x;
|
||||
this.y = (1 - changeAmnt) * this.y + changeAmnt * finalVec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this vector to the interpolation by changeAmnt from beginVec to
|
||||
* finalVec this=(1-changeAmnt)*beginVec + changeAmnt * finalVec
|
||||
*
|
||||
* @param beginVec The begining vector (delta=0)
|
||||
* @param finalVec The final vector to interpolate towards (delta=1)
|
||||
* @param changeAmnt An amount between 0.0 - 1.0 representing a precentage
|
||||
* change from beginVec towards finalVec
|
||||
*/
|
||||
public Vector2f interpolate(
|
||||
Vector2f beginVec,
|
||||
Vector2f finalVec,
|
||||
float changeAmnt
|
||||
) {
|
||||
this.x = (1 - changeAmnt) * beginVec.x + changeAmnt * finalVec.x;
|
||||
this.y = (1 - changeAmnt) * beginVec.y + changeAmnt * finalVec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a vector... if it is null or its floats are NaN or infinite, return
|
||||
* false. Else return true.
|
||||
*
|
||||
* @param vector the vector to check
|
||||
* @return true or false as stated above.
|
||||
*/
|
||||
public static boolean isValidVector(Vector2f vector) {
|
||||
if (vector == null)
|
||||
return false;
|
||||
if (
|
||||
Float.isNaN(vector.x)
|
||||
||
|
||||
Float.isNaN(vector.y)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
Float.isInfinite(vector.x)
|
||||
||
|
||||
Float.isInfinite(vector.y)
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>length</code> calculates the magnitude of this vector.
|
||||
*
|
||||
* @return the length or magnitude of the vector.
|
||||
*/
|
||||
public float length() {
|
||||
return FastMath.sqrt(lengthSquared());
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>lengthSquared</code> calculates the squared value of the magnitude
|
||||
* of the vector.
|
||||
*
|
||||
* @return the magnitude squared of the vector.
|
||||
*/
|
||||
public float lengthSquared() {
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>distanceSquared</code> calculates the distance squared between this
|
||||
* vector and vector v.
|
||||
*
|
||||
* @param v the second vector to determine the distance squared.
|
||||
* @return the distance squared between the two vectors.
|
||||
*/
|
||||
public float distanceSquared(Vector2f v) {
|
||||
double dx = x - v.x;
|
||||
double dy = y - v.y;
|
||||
return (float) (dx * dx + dy * dy);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>distanceSquared</code> calculates the distance squared between this
|
||||
* vector and vector v.
|
||||
*
|
||||
* @param otherX The X coordinate of the v vector
|
||||
* @param otherY The Y coordinate of the v vector
|
||||
* @return the distance squared between the two vectors.
|
||||
*/
|
||||
public float distanceSquared(float otherX, float otherY) {
|
||||
double dx = x - otherX;
|
||||
double dy = y - otherY;
|
||||
return (float) (dx * dx + dy * dy);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>distance</code> calculates the distance between this vector and
|
||||
* vector v.
|
||||
*
|
||||
* @param v the second vector to determine the distance.
|
||||
* @return the distance between the two vectors.
|
||||
*/
|
||||
public float distance(Vector2f v) {
|
||||
return FastMath.sqrt(distanceSquared(v));
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>mult</code> multiplies this vector by a scalar. The resultant
|
||||
* vector is returned.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @return the new vector.
|
||||
*/
|
||||
public Vector2f mult(float scalar) {
|
||||
return new Vector2f(x * scalar, y * scalar);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies this vector by a scalar internally, and
|
||||
* returns a handle to this vector for easy chaining of calls.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f multLocal(float scalar) {
|
||||
x *= scalar;
|
||||
y *= scalar;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to mult to this vector.
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f multLocal(Vector2f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x *= vec.x;
|
||||
y *= vec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies this Vector2f's x and y by the scalar and stores the result in
|
||||
* product. The result is returned for chaining. Similar to
|
||||
* product=this*scalar;
|
||||
*
|
||||
* @param scalar The scalar to multiply by.
|
||||
* @param product The vector2f to store the result in.
|
||||
* @return product, after multiplication.
|
||||
*/
|
||||
public Vector2f mult(float scalar, Vector2f product) {
|
||||
if (null == product) {
|
||||
product = new Vector2f();
|
||||
}
|
||||
|
||||
product.x = x * scalar;
|
||||
product.y = y * scalar;
|
||||
return product;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divide</code> divides the values of this vector by a scalar and
|
||||
* returns the result. The values of this vector remain untouched.
|
||||
*
|
||||
* @param scalar the value to divide this vectors attributes by.
|
||||
* @return the result <code>Vector</code>.
|
||||
*/
|
||||
public Vector2f divide(float scalar) {
|
||||
return new Vector2f(x / scalar, y / scalar);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divideLocal</code> divides this vector by a scalar internally, and
|
||||
* returns a handle to this vector for easy chaining of calls. Dividing by
|
||||
* zero will result in an exception.
|
||||
*
|
||||
* @param scalar the value to divides this vector by.
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f divideLocal(float scalar) {
|
||||
x /= scalar;
|
||||
y /= scalar;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>negate</code> returns the negative of this vector. All values are
|
||||
* negated and set to a new vector.
|
||||
*
|
||||
* @return the negated vector.
|
||||
*/
|
||||
public Vector2f negate() {
|
||||
return new Vector2f(-x, -y);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>negateLocal</code> negates the internal values of this vector.
|
||||
*
|
||||
* @return this.
|
||||
*/
|
||||
public Vector2f negateLocal() {
|
||||
x = -x;
|
||||
y = -y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtract</code> subtracts the values of a given vector from those
|
||||
* of this vector creating a new vector object. If the provided vector is
|
||||
* null, an exception is thrown.
|
||||
*
|
||||
* @param vec the vector to subtract from this vector.
|
||||
* @return the result vector.
|
||||
*/
|
||||
public Vector2f subtract(Vector2f vec) {
|
||||
return subtract(vec, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtract</code> subtracts the values of a given vector from those
|
||||
* of this vector storing the result in the given vector object. If the
|
||||
* provided vector is null, an exception is thrown.
|
||||
*
|
||||
* @param vec the vector to subtract from this vector.
|
||||
* @param store the vector to store the result in. It is safe for this to be
|
||||
* the same as vec. If null, a new vector is created.
|
||||
* @return the result vector.
|
||||
*/
|
||||
public Vector2f subtract(Vector2f vec, Vector2f store) {
|
||||
if (store == null)
|
||||
store = new Vector2f();
|
||||
store.x = x - vec.x;
|
||||
store.y = y - vec.y;
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtract</code> subtracts the given x,y values from those of this
|
||||
* vector creating a new vector object.
|
||||
*
|
||||
* @param valX value to subtract from x
|
||||
* @param valY value to subtract from y
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f subtract(float valX, float valY) {
|
||||
return new Vector2f(x - valX, y - valY);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtractLocal</code> subtracts a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to subtract
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f subtractLocal(Vector2f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x -= vec.x;
|
||||
y -= vec.y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtractLocal</code> subtracts the provided values from this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls.
|
||||
*
|
||||
* @param valX value to subtract from x
|
||||
* @param valY value to subtract from y
|
||||
* @return this
|
||||
*/
|
||||
public Vector2f subtractLocal(float valX, float valY) {
|
||||
x -= valX;
|
||||
y -= valY;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>normalize</code> returns the unit vector of this vector.
|
||||
*
|
||||
* @return unit vector of this vector.
|
||||
*/
|
||||
public Vector2f normalize() {
|
||||
float length = length();
|
||||
if (length != 0) {
|
||||
return divide(length);
|
||||
}
|
||||
|
||||
return divide(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>normalizeLocal</code> makes this vector into a unit vector of
|
||||
* itself.
|
||||
*
|
||||
* @return this.
|
||||
*/
|
||||
public Vector2f normalizeLocal() {
|
||||
float length = length();
|
||||
if (length != 0) {
|
||||
return divideLocal(length);
|
||||
}
|
||||
|
||||
return divideLocal(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>smallestAngleBetween</code> returns (in radians) the minimum angle
|
||||
* between two vectors. It is assumed that both this vector and the given
|
||||
* vector are unit vectors (iow, normalized).
|
||||
*
|
||||
* @param otherVector a unit vector to find the angle against
|
||||
* @return the angle in radians.
|
||||
*/
|
||||
public float smallestAngleBetween(Vector2f otherVector) {
|
||||
float dotProduct = dot(otherVector);
|
||||
float angle = FastMath.acos(dotProduct);
|
||||
return angle;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>angleBetween</code> returns (in radians) the angle required to
|
||||
* rotate a ray represented by this vector to lie colinear to a ray
|
||||
* described by the given vector. It is assumed that both this vector and
|
||||
* the given vector are unit vectors (iow, normalized).
|
||||
*
|
||||
* @param otherVector the "destination" unit vector
|
||||
* @return the angle in radians.
|
||||
*/
|
||||
public float angleBetween(Vector2f otherVector) {
|
||||
float angle = FastMath.atan2(otherVector.y, otherVector.x)
|
||||
- FastMath.atan2(y, x);
|
||||
return angle;
|
||||
}
|
||||
|
||||
public float getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public Vector2f setX(float x) {
|
||||
this.x = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
public float getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public Vector2f setY(float y) {
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>getAngle</code> returns (in radians) the angle represented by this
|
||||
* Vector2f as expressed by a conversion from rectangular coordinates
|
||||
* (<code>x</code>, <code>y</code>) to polar coordinates
|
||||
* (r, <i>theta</i>).
|
||||
*
|
||||
* @return the angle in radians. [-pi, pi)
|
||||
*/
|
||||
public float getAngle() {
|
||||
return FastMath.atan2(y, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>zero</code> resets this vector's data to zero internally.
|
||||
*/
|
||||
public Vector2f zero() {
|
||||
x = y = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>hashCode</code> returns a unique code for this vector object based
|
||||
* on it's values. If two vectors are logically equivalent, they will return
|
||||
* the same hash code value.
|
||||
*
|
||||
* @return the hash code value of this vector.
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 37;
|
||||
hash += 37 * hash + Float.floatToIntBits(x);
|
||||
hash += 37 * hash + Float.floatToIntBits(y);
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector2f clone() {
|
||||
try {
|
||||
return (Vector2f) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError(); // can not happen
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves this Vector2f into the given float[] object.
|
||||
*
|
||||
* @param floats The float[] to take this Vector2f. If null, a new float[2]
|
||||
* is created.
|
||||
* @return The array, with X, Y float values in that order
|
||||
*/
|
||||
public float[] toArray(float[] floats) {
|
||||
if (floats == null) {
|
||||
floats = new float[2];
|
||||
}
|
||||
floats[0] = x;
|
||||
floats[1] = y;
|
||||
return floats;
|
||||
}
|
||||
|
||||
/**
|
||||
* are these two vectors the same? they are is they both have the same x and
|
||||
* y values.
|
||||
*
|
||||
* @param o the object to compare for equality
|
||||
* @return true if they are equal
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Vector2f)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Vector2f comp = (Vector2f) o;
|
||||
if (Float.compare(x, comp.x) != 0)
|
||||
return false;
|
||||
if (Float.compare(y, comp.y) != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>toString</code> returns the string representation of this vector
|
||||
* object. The format of the string is such: com.jme.math.Vector2f
|
||||
* [X=XX.XXXX, Y=YY.YYYY]
|
||||
*
|
||||
* @return the string representation of this vector.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + x + ", " + y + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* Used with serialization. Not to be called manually.
|
||||
*
|
||||
* @param in ObjectInput
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
* @see java.io.Externalizable
|
||||
*/
|
||||
public void readExternal(ObjectInput in) throws IOException,
|
||||
ClassNotFoundException {
|
||||
x = in.readFloat();
|
||||
y = in.readFloat();
|
||||
}
|
||||
|
||||
/**
|
||||
* Used with serialization. Not to be called manually.
|
||||
*
|
||||
* @param out ObjectOutput
|
||||
* @throws IOException
|
||||
* @see java.io.Externalizable
|
||||
*/
|
||||
public void writeExternal(ObjectOutput out) throws IOException {
|
||||
out.writeFloat(x);
|
||||
out.writeFloat(y);
|
||||
}
|
||||
|
||||
public void rotateAroundOrigin(float angle, boolean cw) {
|
||||
if (cw)
|
||||
angle = -angle;
|
||||
float newX = FastMath.cos(angle) * x - FastMath.sin(angle) * y;
|
||||
float newY = FastMath.sin(angle) * x + FastMath.cos(angle) * y;
|
||||
x = newX;
|
||||
y = newY;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,971 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.math;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* <code>Vector4f</code> defines a Vector for a four float value tuple.
|
||||
* <code>Vector4f</code> can represent any four dimensional value, such as a
|
||||
* vertex, a normal, etc. Utility methods are also included to aid in
|
||||
* mathematical calculations.
|
||||
*
|
||||
* @author Maarten Steur
|
||||
*/
|
||||
public final class Vector4f implements Cloneable, java.io.Serializable {
|
||||
|
||||
static final long serialVersionUID = 1;
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Vector4f.class.getName());
|
||||
|
||||
public final static Vector4f ZERO = new Vector4f(0, 0, 0, 0);
|
||||
public final static Vector4f NAN = new Vector4f(Float.NaN, Float.NaN, Float.NaN, Float.NaN);
|
||||
public final static Vector4f UNIT_X = new Vector4f(1, 0, 0, 0);
|
||||
public final static Vector4f UNIT_Y = new Vector4f(0, 1, 0, 0);
|
||||
public final static Vector4f UNIT_Z = new Vector4f(0, 0, 1, 0);
|
||||
public final static Vector4f UNIT_W = new Vector4f(0, 0, 0, 1);
|
||||
public final static Vector4f UNIT_XYZW = new Vector4f(1, 1, 1, 1);
|
||||
public final static Vector4f POSITIVE_INFINITY = new Vector4f(
|
||||
Float.POSITIVE_INFINITY,
|
||||
Float.POSITIVE_INFINITY,
|
||||
Float.POSITIVE_INFINITY,
|
||||
Float.POSITIVE_INFINITY
|
||||
);
|
||||
public final static Vector4f NEGATIVE_INFINITY = new Vector4f(
|
||||
Float.NEGATIVE_INFINITY,
|
||||
Float.NEGATIVE_INFINITY,
|
||||
Float.NEGATIVE_INFINITY,
|
||||
Float.NEGATIVE_INFINITY
|
||||
);
|
||||
|
||||
/**
|
||||
* the x value of the vector.
|
||||
*/
|
||||
public float x;
|
||||
|
||||
/**
|
||||
* the y value of the vector.
|
||||
*/
|
||||
public float y;
|
||||
|
||||
/**
|
||||
* the z value of the vector.
|
||||
*/
|
||||
public float z;
|
||||
|
||||
/**
|
||||
* the w value of the vector.
|
||||
*/
|
||||
public float w;
|
||||
|
||||
/**
|
||||
* Constructor instantiates a new <code>Vector3f</code> with default values
|
||||
* of (0,0,0).
|
||||
*
|
||||
*/
|
||||
public Vector4f() {
|
||||
x = y = z = w = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor instantiates a new <code>Vector4f</code> with provides
|
||||
* values.
|
||||
*
|
||||
* @param x the x value of the vector.
|
||||
* @param y the y value of the vector.
|
||||
* @param z the z value of the vector.
|
||||
* @param w the w value of the vector.
|
||||
*/
|
||||
public Vector4f(float x, float y, float z, float w) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.w = w;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor instantiates a new <code>Vector3f</code> that is a copy of
|
||||
* the provided vector
|
||||
*
|
||||
* @param copy The Vector3f to copy
|
||||
*/
|
||||
public Vector4f(Vector4f copy) {
|
||||
this.set(copy);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>set</code> sets the x,y,z,w values of the vector based on passed
|
||||
* parameters.
|
||||
*
|
||||
* @param x the x value of the vector.
|
||||
* @param y the y value of the vector.
|
||||
* @param z the z value of the vector.
|
||||
* @param w the w value of the vector.
|
||||
* @return this vector
|
||||
*/
|
||||
public Vector4f set(float x, float y, float z, float w) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.w = w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>set</code> sets the x,y,z values of the vector by copying the
|
||||
* supplied vector.
|
||||
*
|
||||
* @param vect the vector to copy.
|
||||
* @return this vector
|
||||
*/
|
||||
public Vector4f set(Vector4f vect) {
|
||||
this.x = vect.x;
|
||||
this.y = vect.y;
|
||||
this.z = vect.z;
|
||||
this.w = vect.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>add</code> adds a provided vector to this vector creating a
|
||||
* resultant vector which is returned. If the provided vector is null, null
|
||||
* is returned.
|
||||
*
|
||||
* @param vec the vector to add to this.
|
||||
* @return the resultant vector.
|
||||
*/
|
||||
public Vector4f add(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
return new Vector4f(x + vec.x, y + vec.y, z + vec.z, w + vec.w);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>add</code> adds the values of a provided vector storing the values
|
||||
* in the supplied vector.
|
||||
*
|
||||
* @param vec the vector to add to this
|
||||
* @param result the vector to store the result in
|
||||
* @return result returns the supplied result vector.
|
||||
*/
|
||||
public Vector4f add(Vector4f vec, Vector4f result) {
|
||||
result.x = x + vec.x;
|
||||
result.y = y + vec.y;
|
||||
result.z = z + vec.z;
|
||||
result.w = w + vec.w;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>addLocal</code> adds a provided vector to this vector internally,
|
||||
* and returns a handle to this vector for easy chaining of calls. If the
|
||||
* provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to add to this vector.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f addLocal(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x += vec.x;
|
||||
y += vec.y;
|
||||
z += vec.z;
|
||||
w += vec.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>add</code> adds the provided values to this vector, creating a new
|
||||
* vector that is then returned.
|
||||
*
|
||||
* @param addX the x value to add.
|
||||
* @param addY the y value to add.
|
||||
* @param addZ the z value to add.
|
||||
* @return the result vector.
|
||||
*/
|
||||
public Vector4f add(float addX, float addY, float addZ, float addW) {
|
||||
return new Vector4f(x + addX, y + addY, z + addZ, w + addW);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>addLocal</code> adds the provided values to this vector internally,
|
||||
* and returns a handle to this vector for easy chaining of calls.
|
||||
*
|
||||
* @param addX value to add to x
|
||||
* @param addY value to add to y
|
||||
* @param addZ value to add to z
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f addLocal(float addX, float addY, float addZ, float addW) {
|
||||
x += addX;
|
||||
y += addY;
|
||||
z += addZ;
|
||||
w += addW;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>scaleAdd</code> multiplies this vector by a scalar then adds the
|
||||
* given Vector3f.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @param add the value to add
|
||||
*/
|
||||
public Vector4f scaleAdd(float scalar, Vector4f add) {
|
||||
x = x * scalar + add.x;
|
||||
y = y * scalar + add.y;
|
||||
z = z * scalar + add.z;
|
||||
w = w * scalar + add.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>scaleAdd</code> multiplies the given vector by a scalar then adds
|
||||
* the given vector.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @param mult the value to multiply the scalar by
|
||||
* @param add the value to add
|
||||
*/
|
||||
public Vector4f scaleAdd(float scalar, Vector4f mult, Vector4f add) {
|
||||
this.x = mult.x * scalar + add.x;
|
||||
this.y = mult.y * scalar + add.y;
|
||||
this.z = mult.z * scalar + add.z;
|
||||
this.w = mult.w * scalar + add.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>dot</code> calculates the dot product of this vector with a
|
||||
* provided vector. If the provided vector is null, 0 is returned.
|
||||
*
|
||||
* @param vec the vector to dot with this vector.
|
||||
* @return the resultant dot product of this vector and a given vector.
|
||||
*/
|
||||
public float dot(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, 0 returned.");
|
||||
return 0;
|
||||
}
|
||||
return x * vec.x + y * vec.y + z * vec.z + w * vec.w;
|
||||
}
|
||||
|
||||
public Vector4f project(Vector4f other) {
|
||||
float n = this.dot(other); // A . B
|
||||
float d = other.lengthSquared(); // |B|^2
|
||||
return new Vector4f(other).normalizeLocal().multLocal(n / d);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this vector is a unit vector (length() ~= 1), returns
|
||||
* false otherwise.
|
||||
*
|
||||
* @return true if this vector is a unit vector (length() ~= 1), or false
|
||||
* otherwise.
|
||||
*/
|
||||
public boolean isUnitVector() {
|
||||
float len = length();
|
||||
return 0.99f < len && len < 1.01f;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>length</code> calculates the magnitude of this vector.
|
||||
*
|
||||
* @return the length or magnitude of the vector.
|
||||
*/
|
||||
public float length() {
|
||||
return FastMath.sqrt(lengthSquared());
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>lengthSquared</code> calculates the squared value of the magnitude
|
||||
* of the vector.
|
||||
*
|
||||
* @return the magnitude squared of the vector.
|
||||
*/
|
||||
public float lengthSquared() {
|
||||
return x * x + y * y + z * z + w * w;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>distanceSquared</code> calculates the distance squared between this
|
||||
* vector and vector v.
|
||||
*
|
||||
* @param v the second vector to determine the distance squared.
|
||||
* @return the distance squared between the two vectors.
|
||||
*/
|
||||
public float distanceSquared(Vector4f v) {
|
||||
double dx = x - v.x;
|
||||
double dy = y - v.y;
|
||||
double dz = z - v.z;
|
||||
double dw = w - v.w;
|
||||
return (float) (dx * dx + dy * dy + dz * dz + dw * dw);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>distance</code> calculates the distance between this vector and
|
||||
* vector v.
|
||||
*
|
||||
* @param v the second vector to determine the distance.
|
||||
* @return the distance between the two vectors.
|
||||
*/
|
||||
public float distance(Vector4f v) {
|
||||
return FastMath.sqrt(distanceSquared(v));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>mult</code> multiplies this vector by a scalar. The resultant
|
||||
* vector is returned.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @return the new vector.
|
||||
*/
|
||||
public Vector4f mult(float scalar) {
|
||||
return new Vector4f(x * scalar, y * scalar, z * scalar, w * scalar);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>mult</code> multiplies this vector by a scalar. The resultant
|
||||
* vector is supplied as the second parameter and returned.
|
||||
*
|
||||
* @param scalar the scalar to multiply this vector by.
|
||||
* @param product the product to store the result in.
|
||||
* @return product
|
||||
*/
|
||||
public Vector4f mult(float scalar, Vector4f product) {
|
||||
if (null == product) {
|
||||
product = new Vector4f();
|
||||
}
|
||||
|
||||
product.x = x * scalar;
|
||||
product.y = y * scalar;
|
||||
product.z = z * scalar;
|
||||
product.w = w * scalar;
|
||||
return product;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies this vector by a scalar internally, and
|
||||
* returns a handle to this vector for easy chaining of calls.
|
||||
*
|
||||
* @param scalar the value to multiply this vector by.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f multLocal(float scalar) {
|
||||
x *= scalar;
|
||||
y *= scalar;
|
||||
z *= scalar;
|
||||
w *= scalar;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to mult to this vector.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f multLocal(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x *= vec.x;
|
||||
y *= vec.y;
|
||||
z *= vec.z;
|
||||
w *= vec.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies this vector by 3 scalars internally,
|
||||
* and returns a handle to this vector for easy chaining of calls.
|
||||
*
|
||||
* @param x
|
||||
* @param y
|
||||
* @param z
|
||||
* @param w
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f multLocal(float x, float y, float z, float w) {
|
||||
this.x *= x;
|
||||
this.y *= y;
|
||||
this.z *= z;
|
||||
this.w *= w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to mult to this vector.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f mult(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
return mult(vec, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>multLocal</code> multiplies a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to mult to this vector.
|
||||
* @param store result vector (null to create a new vector)
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f mult(Vector4f vec, Vector4f store) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
if (store == null)
|
||||
store = new Vector4f();
|
||||
return store.set(x * vec.x, y * vec.y, z * vec.z, w * vec.w);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divide</code> divides the values of this vector by a scalar and
|
||||
* returns the result. The values of this vector remain untouched.
|
||||
*
|
||||
* @param scalar the value to divide this vectors attributes by.
|
||||
* @return the result <code>Vector</code>.
|
||||
*/
|
||||
public Vector4f divide(float scalar) {
|
||||
scalar = 1f / scalar;
|
||||
return new Vector4f(x * scalar, y * scalar, z * scalar, w * scalar);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divideLocal</code> divides this vector by a scalar internally, and
|
||||
* returns a handle to this vector for easy chaining of calls. Dividing by
|
||||
* zero will result in an exception.
|
||||
*
|
||||
* @param scalar the value to divides this vector by.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f divideLocal(float scalar) {
|
||||
scalar = 1f / scalar;
|
||||
x *= scalar;
|
||||
y *= scalar;
|
||||
z *= scalar;
|
||||
w *= scalar;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divide</code> divides the values of this vector by a scalar and
|
||||
* returns the result. The values of this vector remain untouched.
|
||||
*
|
||||
* @param scalar the value to divide this vectors attributes by.
|
||||
* @return the result <code>Vector</code>.
|
||||
*/
|
||||
public Vector4f divide(Vector4f scalar) {
|
||||
return new Vector4f(x / scalar.x, y / scalar.y, z / scalar.z, w / scalar.w);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>divideLocal</code> divides this vector by a scalar internally, and
|
||||
* returns a handle to this vector for easy chaining of calls. Dividing by
|
||||
* zero will result in an exception.
|
||||
*
|
||||
* @param scalar the value to divides this vector by.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f divideLocal(Vector4f scalar) {
|
||||
x /= scalar.x;
|
||||
y /= scalar.y;
|
||||
z /= scalar.z;
|
||||
w /= scalar.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>negate</code> returns the negative of this vector. All values are
|
||||
* negated and set to a new vector.
|
||||
*
|
||||
* @return the negated vector.
|
||||
*/
|
||||
public Vector4f negate() {
|
||||
return new Vector4f(-x, -y, -z, -w);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>negateLocal</code> negates the internal values of this vector.
|
||||
*
|
||||
* @return this.
|
||||
*/
|
||||
public Vector4f negateLocal() {
|
||||
x = -x;
|
||||
y = -y;
|
||||
z = -z;
|
||||
w = -w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>subtract</code> subtracts the values of a given vector from those
|
||||
* of this vector creating a new vector object. If the provided vector is
|
||||
* null, null is returned.
|
||||
*
|
||||
* @param vec the vector to subtract from this vector.
|
||||
* @return the result vector.
|
||||
*/
|
||||
public Vector4f subtract(Vector4f vec) {
|
||||
return new Vector4f(x - vec.x, y - vec.y, z - vec.z, w - vec.w);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtractLocal</code> subtracts a provided vector to this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls. If the provided vector is null, null is returned.
|
||||
*
|
||||
* @param vec the vector to subtract
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f subtractLocal(Vector4f vec) {
|
||||
if (null == vec) {
|
||||
logger.warning("Provided vector is null, null returned.");
|
||||
return null;
|
||||
}
|
||||
x -= vec.x;
|
||||
y -= vec.y;
|
||||
z -= vec.z;
|
||||
w -= vec.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>subtract</code>
|
||||
*
|
||||
* @param vec the vector to subtract from this
|
||||
* @param result the vector to store the result in
|
||||
* @return result
|
||||
*/
|
||||
public Vector4f subtract(Vector4f vec, Vector4f result) {
|
||||
if (result == null) {
|
||||
result = new Vector4f();
|
||||
}
|
||||
result.x = x - vec.x;
|
||||
result.y = y - vec.y;
|
||||
result.z = z - vec.z;
|
||||
result.w = w - vec.w;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <code>subtract</code> subtracts the provided values from this vector,
|
||||
* creating a new vector that is then returned.
|
||||
*
|
||||
* @param subtractX the x value to subtract.
|
||||
* @param subtractY the y value to subtract.
|
||||
* @param subtractZ the z value to subtract.
|
||||
* @param subtractW the w value to subtract.
|
||||
* @return the result vector.
|
||||
*/
|
||||
public Vector4f subtract(float subtractX, float subtractY, float subtractZ, float subtractW) {
|
||||
return new Vector4f(x - subtractX, y - subtractY, z - subtractZ, w - subtractW);
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>subtractLocal</code> subtracts the provided values from this vector
|
||||
* internally, and returns a handle to this vector for easy chaining of
|
||||
* calls.
|
||||
*
|
||||
* @param subtractX the x value to subtract.
|
||||
* @param subtractY the y value to subtract.
|
||||
* @param subtractZ the z value to subtract.
|
||||
* @param subtractW the w value to subtract.
|
||||
* @return this
|
||||
*/
|
||||
public Vector4f subtractLocal(
|
||||
float subtractX,
|
||||
float subtractY,
|
||||
float subtractZ,
|
||||
float subtractW
|
||||
) {
|
||||
x -= subtractX;
|
||||
y -= subtractY;
|
||||
z -= subtractZ;
|
||||
w -= subtractW;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>normalize</code> returns the unit vector of this vector.
|
||||
*
|
||||
* @return unit vector of this vector.
|
||||
*/
|
||||
public Vector4f normalize() {
|
||||
// float length = length();
|
||||
// if (length != 0) {
|
||||
// return divide(length);
|
||||
// }
|
||||
//
|
||||
// return divide(1);
|
||||
float length = x * x + y * y + z * z + w * w;
|
||||
if (length != 1f && length != 0f) {
|
||||
length = 1.0f / FastMath.sqrt(length);
|
||||
return new Vector4f(x * length, y * length, z * length, w * length);
|
||||
}
|
||||
return clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>normalizeLocal</code> makes this vector into a unit vector of
|
||||
* itself.
|
||||
*
|
||||
* @return this.
|
||||
*/
|
||||
public Vector4f normalizeLocal() {
|
||||
// NOTE: this implementation is more optimized
|
||||
// than the old jme normalize as this method
|
||||
// is commonly used.
|
||||
float length = x * x + y * y + z * z + w * w;
|
||||
if (length != 1f && length != 0f) {
|
||||
length = 1.0f / FastMath.sqrt(length);
|
||||
x *= length;
|
||||
y *= length;
|
||||
z *= length;
|
||||
w *= length;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>maxLocal</code> computes the maximum value for each component in
|
||||
* this and <code>other</code> vector. The result is stored in this vector.
|
||||
*
|
||||
* @param other
|
||||
*/
|
||||
public Vector4f maxLocal(Vector4f other) {
|
||||
x = other.x > x ? other.x : x;
|
||||
y = other.y > y ? other.y : y;
|
||||
z = other.z > z ? other.z : z;
|
||||
w = other.w > w ? other.w : w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>minLocal</code> computes the minimum value for each component in
|
||||
* this and <code>other</code> vector. The result is stored in this vector.
|
||||
*
|
||||
* @param other
|
||||
*/
|
||||
public Vector4f minLocal(Vector4f other) {
|
||||
x = other.x < x ? other.x : x;
|
||||
y = other.y < y ? other.y : y;
|
||||
z = other.z < z ? other.z : z;
|
||||
w = other.w < w ? other.w : w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>zero</code> resets this vector's data to zero internally.
|
||||
*/
|
||||
public Vector4f zero() {
|
||||
x = y = z = w = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>angleBetween</code> returns (in radians) the angle between two
|
||||
* vectors. It is assumed that both this vector and the given vector are
|
||||
* unit vectors (iow, normalized).
|
||||
*
|
||||
* @param otherVector a unit vector to find the angle against
|
||||
* @return the angle in radians.
|
||||
*/
|
||||
public float angleBetween(Vector4f otherVector) {
|
||||
float dotProduct = dot(otherVector);
|
||||
float angle = FastMath.acos(dotProduct);
|
||||
return angle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this vector to the interpolation by changeAmnt from this to the
|
||||
* finalVec this=(1-changeAmnt)*this + changeAmnt * finalVec
|
||||
*
|
||||
* @param finalVec The final vector to interpolate towards
|
||||
* @param changeAmnt An amount between 0.0 - 1.0 representing a precentage
|
||||
* change from this towards finalVec
|
||||
*/
|
||||
public Vector4f interpolate(Vector4f finalVec, float changeAmnt) {
|
||||
this.x = (1 - changeAmnt) * this.x + changeAmnt * finalVec.x;
|
||||
this.y = (1 - changeAmnt) * this.y + changeAmnt * finalVec.y;
|
||||
this.z = (1 - changeAmnt) * this.z + changeAmnt * finalVec.z;
|
||||
this.w = (1 - changeAmnt) * this.w + changeAmnt * finalVec.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets this vector to the interpolation by changeAmnt from beginVec to
|
||||
* finalVec this=(1-changeAmnt)*beginVec + changeAmnt * finalVec
|
||||
*
|
||||
* @param beginVec the beging vector (changeAmnt=0)
|
||||
* @param finalVec The final vector to interpolate towards
|
||||
* @param changeAmnt An amount between 0.0 - 1.0 representing a precentage
|
||||
* change from beginVec towards finalVec
|
||||
*/
|
||||
public Vector4f interpolate(Vector4f beginVec, Vector4f finalVec, float changeAmnt) {
|
||||
this.x = (1 - changeAmnt) * beginVec.x + changeAmnt * finalVec.x;
|
||||
this.y = (1 - changeAmnt) * beginVec.y + changeAmnt * finalVec.y;
|
||||
this.z = (1 - changeAmnt) * beginVec.z + changeAmnt * finalVec.z;
|
||||
this.w = (1 - changeAmnt) * beginVec.w + changeAmnt * finalVec.w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a vector... if it is null or its floats are NaN or infinite, return
|
||||
* false. Else return true.
|
||||
*
|
||||
* @param vector the vector to check
|
||||
* @return true or false as stated above.
|
||||
*/
|
||||
public static boolean isValidVector(Vector4f vector) {
|
||||
if (vector == null)
|
||||
return false;
|
||||
if (
|
||||
Float.isNaN(vector.x)
|
||||
||
|
||||
Float.isNaN(vector.y)
|
||||
||
|
||||
Float.isNaN(vector.z)
|
||||
||
|
||||
Float.isNaN(vector.w)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
Float.isInfinite(vector.x)
|
||||
||
|
||||
Float.isInfinite(vector.y)
|
||||
||
|
||||
Float.isInfinite(vector.z)
|
||||
||
|
||||
Float.isInfinite(vector.w)
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector4f clone() {
|
||||
try {
|
||||
return (Vector4f) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new AssertionError(); // can not happen
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves this Vector3f into the given float[] object.
|
||||
*
|
||||
* @param floats The float[] to take this Vector3f. If null, a new float[3]
|
||||
* is created.
|
||||
* @return The array, with X, Y, Z float values in that order
|
||||
*/
|
||||
public float[] toArray(float[] floats) {
|
||||
if (floats == null) {
|
||||
floats = new float[4];
|
||||
}
|
||||
floats[0] = x;
|
||||
floats[1] = y;
|
||||
floats[2] = z;
|
||||
floats[3] = w;
|
||||
return floats;
|
||||
}
|
||||
|
||||
/**
|
||||
* are these two vectors the same? they are is they both have the same x,y,
|
||||
* and z values.
|
||||
*
|
||||
* @param o the object to compare for equality
|
||||
* @return true if they are equal
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Vector4f)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Vector4f comp = (Vector4f) o;
|
||||
if (Float.compare(x, comp.x) != 0)
|
||||
return false;
|
||||
if (Float.compare(y, comp.y) != 0)
|
||||
return false;
|
||||
if (Float.compare(z, comp.z) != 0)
|
||||
return false;
|
||||
if (Float.compare(w, comp.w) != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>hashCode</code> returns a unique code for this vector object based
|
||||
* on it's values. If two vectors are logically equivalent, they will return
|
||||
* the same hash code value.
|
||||
*
|
||||
* @return the hash code value of this vector.
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 37;
|
||||
hash += 37 * hash + Float.floatToIntBits(x);
|
||||
hash += 37 * hash + Float.floatToIntBits(y);
|
||||
hash += 37 * hash + Float.floatToIntBits(z);
|
||||
hash += 37 * hash + Float.floatToIntBits(w);
|
||||
return hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* <code>toString</code> returns the string representation of this vector.
|
||||
* The format is:
|
||||
*
|
||||
* org.jme.math.Vector3f [X=XX.XXXX, Y=YY.YYYY, Z=ZZ.ZZZZ, W=WW.WWWW]
|
||||
*
|
||||
* @return the string representation of this vector.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + x + ", " + y + ", " + z + ", " + w + ")";
|
||||
}
|
||||
|
||||
public float getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public Vector4f setX(float x) {
|
||||
this.x = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
public float getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public Vector4f setY(float y) {
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
public float getZ() {
|
||||
return z;
|
||||
}
|
||||
|
||||
public Vector4f setZ(float z) {
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public float getW() {
|
||||
return w;
|
||||
}
|
||||
|
||||
public Vector4f setW(float w) {
|
||||
this.w = w;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index
|
||||
* @return x value if index == 0, y value if index == 1 or z value if index
|
||||
* == 2
|
||||
* @throws IllegalArgumentException if index is not one of 0, 1, 2.
|
||||
*/
|
||||
public float get(int index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
return x;
|
||||
case 1:
|
||||
return y;
|
||||
case 2:
|
||||
return z;
|
||||
case 3:
|
||||
return w;
|
||||
}
|
||||
throw new IllegalArgumentException("index must be either 0, 1, 2 or 3");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index which field index in this vector to set.
|
||||
* @param value to set to one of x, y, z or w.
|
||||
* @throws IllegalArgumentException if index is not one of 0, 1, 2, 3.
|
||||
*/
|
||||
public void set(int index, float value) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
x = value;
|
||||
return;
|
||||
case 1:
|
||||
y = value;
|
||||
return;
|
||||
case 2:
|
||||
z = value;
|
||||
return;
|
||||
case 3:
|
||||
w = value;
|
||||
return;
|
||||
}
|
||||
throw new IllegalArgumentException("index must be either 0, 1, 2 or 3");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.system;
|
||||
|
||||
/**
|
||||
* <code>NanoTimer</code> is a System.nanoTime implementation of
|
||||
* <code>Timer</code>. This is primarily useful for headless applications
|
||||
* running on a server.
|
||||
*
|
||||
* @author Matthew D. Hicks
|
||||
*/
|
||||
public class NanoTimer extends Timer {
|
||||
|
||||
private static final long TIMER_RESOLUTION = 1000000000L;
|
||||
private static final float INVERSE_TIMER_RESOLUTION = 1f / TIMER_RESOLUTION;
|
||||
|
||||
private long startTime;
|
||||
private long previousTime;
|
||||
private float tpf;
|
||||
private float fps;
|
||||
private long currentTime;
|
||||
|
||||
public NanoTimer() {
|
||||
startTime = System.nanoTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time in seconds. The timer starts at 0.0 seconds.
|
||||
*
|
||||
* @return the current time in seconds
|
||||
*/
|
||||
|
||||
protected long getTimeInternal() {
|
||||
return System.nanoTime() - startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTimeInSeconds() {
|
||||
return getTime() * INVERSE_TIMER_RESOLUTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTime() {
|
||||
return currentTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getResolution() {
|
||||
return TIMER_RESOLUTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getFrameRate() {
|
||||
return fps;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTimePerFrame() {
|
||||
return tpf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
currentTime = getTimeInternal();
|
||||
tpf = (currentTime - previousTime) * (1.0f / TIMER_RESOLUTION);
|
||||
fps = 1.0f / tpf;
|
||||
previousTime = getTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
startTime = System.nanoTime();
|
||||
currentTime = getTimeInternal();
|
||||
previousTime = getTime();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.system;
|
||||
|
||||
/**
|
||||
* <code>Timer</code> is the base class for a high resolution timer. It is
|
||||
* created from getTimer("display system")
|
||||
*
|
||||
* @author Mark Powell
|
||||
* @version $Id: Timer.java,v 1.18 2007/03/09 10:19:34 rherlitz Exp $
|
||||
*/
|
||||
public abstract class Timer {
|
||||
|
||||
/**
|
||||
* Returns the current time in ticks. A tick is an arbitrary measure of time
|
||||
* defined by the timer implementation. The number of ticks per second is
|
||||
* given by <code>getResolution()</code>. The timer starts at 0 ticks.
|
||||
*
|
||||
* @return a long value representing the current time
|
||||
*/
|
||||
public abstract long getTime();
|
||||
|
||||
/**
|
||||
* Returns the time in seconds. The timer starts at 0.0 seconds.
|
||||
*
|
||||
* @return the current time in seconds
|
||||
*/
|
||||
public float getTimeInSeconds() {
|
||||
return getTime() / (float) getResolution();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the resolution of the timer.
|
||||
*
|
||||
* @return the number of timer ticks per second
|
||||
*/
|
||||
public abstract long getResolution();
|
||||
|
||||
/**
|
||||
* Returns the "calls per second". If this is called every frame, then it
|
||||
* will return the "frames per second".
|
||||
*
|
||||
* @return The "calls per second".
|
||||
*/
|
||||
public abstract float getFrameRate();
|
||||
|
||||
/**
|
||||
* Returns the time, in seconds, between the last call and the current one.
|
||||
*
|
||||
* @return Time between this call and the last one.
|
||||
*/
|
||||
public abstract float getTimePerFrame();
|
||||
|
||||
/**
|
||||
* <code>update</code> recalculates the frame rate based on the previous
|
||||
* call to update. It is assumed that update is called each frame.
|
||||
*/
|
||||
public abstract void update();
|
||||
|
||||
/**
|
||||
* Reset the timer to 0. Clear any tpf history.
|
||||
*/
|
||||
public abstract void reset();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
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