This commit is contained in:
Yamo4490 2025-11-29 16:18:19 +09:00
commit 30c4d469c9
89 changed files with 353 additions and 9556 deletions

View File

@ -38,12 +38,16 @@ namespace KindRetargeting
[HideInInspector] public float HipsWeightOffset = 1f;
// 로컬-월드 축 방향 정규화 계수
private Vector3 axisNormalizer = Vector3.one;
// 축 매핑: 월드 방향(Right/Up/Forward)을 담당하는 로컬 축을 저장
// 예: localAxisForWorldRight = (0, 0, 1) 이면 로컬 Z축이 월드 Right 방향을 담당
// 부호는 방향을 나타냄: (0, 0, -1)이면 로컬 -Z가 월드 Right를 담당
private Vector3 localAxisForWorldRight = Vector3.right; // 월드 좌우(Right)를 담당하는 로컬 축
private Vector3 localAxisForWorldUp = Vector3.up; // 월드 상하(Up)를 담당하는 로컬 축
private Vector3 localAxisForWorldForward = Vector3.forward; // 월드 앞뒤(Forward)를 담당하는 로컬 축
[Header("축 정규화 정보 (읽기 전용)")]
[SerializeField, HideInInspector]
private Vector3 debugAxisNormalizer = Vector3.one;
[SerializeField]
public Vector3 debugAxisNormalizer = Vector3.one;
// HumanPoseHandler를 이용하여 원본 및 대상 아바타의 포즈를 관리
private HumanPoseHandler sourcePoseHandler;
@ -86,6 +90,12 @@ namespace KindRetargeting
[SerializeField, Range(-1f, 1f)]
private float kneeFrontBackWeight = 0.4f; // 무릎 앞/뒤 위치 조정 가중치
[Header("발 IK 위치 조정")]
[SerializeField, Range(-1f, 1f)]
private float footFrontBackOffset = 0f; // 발 앞뒤 오프셋 (+: 앞, -: 뒤)
[SerializeField, Range(-1f, 1f)]
private float footInOutOffset = 0f; // 발 안쪽/바깥쪽 오프셋 (+: 벌리기, -: 모으기)
[Header("바닥 높이 조정")]
[SerializeField, Range(-1f, 1f)] public float floorHeight = 0f; // 바닥 높이 조정값
@ -135,6 +145,8 @@ namespace KindRetargeting
public float hipsOffsetZ;
public float kneeInOutWeight;
public float kneeFrontBackWeight;
public float footFrontBackOffset; // 발 앞뒤 오프셋
public float footInOutOffset; // 발 안쪽/바깥쪽 오프셋
public float floorHeight;
public EnumsList.FingerCopyMode fingerCopyMode;
public bool useMotionFilter;
@ -151,6 +163,40 @@ namespace KindRetargeting
// 각 손가락 관절별로 필터 버퍼를 관리하는 Dictionary 추가
private Dictionary<int, Queue<float>> fingerFilterBuffers = new Dictionary<int, Queue<float>>();
// CopyFingerPoseByMuscle에서 사용할 본 Transform 저장용 (메모리 재사용)
private Dictionary<HumanBodyBones, (Vector3 position, Quaternion rotation)> savedBoneTransforms =
new Dictionary<HumanBodyBones, (Vector3, Quaternion)>();
// 손가락을 제외한 모든 휴먼본 목록 (캐싱)
private static readonly HumanBodyBones[] nonFingerBones = new HumanBodyBones[]
{
HumanBodyBones.Hips,
HumanBodyBones.Spine,
HumanBodyBones.Chest,
HumanBodyBones.UpperChest,
HumanBodyBones.Neck,
HumanBodyBones.Head,
HumanBodyBones.LeftShoulder,
HumanBodyBones.LeftUpperArm,
HumanBodyBones.LeftLowerArm,
HumanBodyBones.LeftHand,
HumanBodyBones.RightShoulder,
HumanBodyBones.RightUpperArm,
HumanBodyBones.RightLowerArm,
HumanBodyBones.RightHand,
HumanBodyBones.LeftUpperLeg,
HumanBodyBones.LeftLowerLeg,
HumanBodyBones.LeftFoot,
HumanBodyBones.LeftToes,
HumanBodyBones.RightUpperLeg,
HumanBodyBones.RightLowerLeg,
HumanBodyBones.RightFoot,
HumanBodyBones.RightToes,
HumanBodyBones.LeftEye,
HumanBodyBones.RightEye,
HumanBodyBones.Jaw
};
// IK 조인트 싱을 위한 구조체
private struct IKJoints
{
@ -220,8 +266,15 @@ namespace KindRetargeting
}
/// <summary>
/// 타겟 아바타의 로컬 축과 월드 축의 관계를 분석하여 정규화 계수를 계산합니다.
/// 이를 통해 사용자는 항상 직관적인 방향(앞/뒤/위/아래)으로 제어할 수 있습니다.
/// 타겟 아바타의 로컬 축과 월드 축의 관계를 분석하여 축 매핑을 계산합니다.
/// T-포즈 상태에서 힙의 각 로컬 축이 월드의 어느 방향을 가리키는지 분석합니다.
///
/// 예시:
/// - 아바타 A: 로컬 Y가 월드 Up을 가리킴 → localAxisForWorldUp = (0, 1, 0)
/// - 아바타 B: 로컬 Z가 월드 Up을 가리킴 → localAxisForWorldUp = (0, 0, 1)
/// - 아바타 C: 로컬 -Z가 월드 Up을 가리킴 → localAxisForWorldUp = (0, 0, -1)
///
/// 이를 통해 hipsOffsetY는 항상 "위/아래" 방향으로 작동합니다.
/// </summary>
private void CalculateAxisNormalizer()
{
@ -230,46 +283,85 @@ namespace KindRetargeting
Transform hips = targetAnimator.GetBoneTransform(HumanBodyBones.Hips);
if (hips == null) return;
// 힙의 초기 로컬 축 방향을 월드 공간으로 변환
Vector3 localRight = hips.TransformDirection(Vector3.right);
Vector3 localUp = hips.TransformDirection(Vector3.up);
Vector3 localForward = hips.TransformDirection(Vector3.forward);
// 힙의 각 로컬 축을 월드 공간으로 변환
Vector3 localXInWorld = hips.TransformDirection(Vector3.right).normalized;
Vector3 localYInWorld = hips.TransformDirection(Vector3.up).normalized;
Vector3 localZInWorld = hips.TransformDirection(Vector3.forward).normalized;
// 각 로컬 축이 월드의 어느 축과 가장 가까운지 판단
axisNormalizer = new Vector3(
GetAxisSign(localRight, Vector3.right), // X축 정규화
GetAxisSign(localUp, Vector3.up), // Y축 정규화
GetAxisSign(localForward, Vector3.forward) // Z축 정규화
// 월드 Right(X)에 가장 가까운 로컬 축 찾기
localAxisForWorldRight = FindBestLocalAxisForWorld(localXInWorld, localYInWorld, localZInWorld, Vector3.right, out string rightAxisName);
// 월드 Up(Y)에 가장 가까운 로컬 축 찾기
localAxisForWorldUp = FindBestLocalAxisForWorld(localXInWorld, localYInWorld, localZInWorld, Vector3.up, out string upAxisName);
// 월드 Forward(Z)에 가장 가까운 로컬 축 찾기
localAxisForWorldForward = FindBestLocalAxisForWorld(localXInWorld, localYInWorld, localZInWorld, Vector3.forward, out string forwardAxisName);
// 디버그용: 각 오프셋이 어느 로컬 축에 매핑되는지 표시
// X: 좌우 오프셋이 사용하는 로컬 축 (1=X, 2=Y, 3=Z, 부호는 방향)
// Y: 상하 오프셋이 사용하는 로컬 축
// Z: 앞뒤 오프셋이 사용하는 로컬 축
debugAxisNormalizer = new Vector3(
GetAxisIndex(localAxisForWorldRight),
GetAxisIndex(localAxisForWorldUp),
GetAxisIndex(localAxisForWorldForward)
);
debugAxisNormalizer = axisNormalizer; // Inspector 표시용
Debug.Log($"[{gameObject.name}] 축 정규화 계수:\n" +
$" X(좌우): {axisNormalizer.x} (로컬 Right {(axisNormalizer.x > 0 ? "" : "")} 월드 Right)\n" +
$" Y(상하): {axisNormalizer.y} (로컬 Up {(axisNormalizer.y > 0 ? "" : "")} 월드 Up)\n" +
$" Z(앞뒤): {axisNormalizer.z} (로컬 Forward {(axisNormalizer.z > 0 ? "" : "")} 월드 Forward)");
Debug.Log($"[{gameObject.name}] 축 매핑 분석 완료:\n" +
$" 월드 Right(좌우) ← 로컬 {rightAxisName} → 매핑: {localAxisForWorldRight}\n" +
$" 월드 Up(상하) ← 로컬 {upAxisName} → 매핑: {localAxisForWorldUp}\n" +
$" 월드 Forward(앞뒤) ← 로컬 {forwardAxisName} → 매핑: {localAxisForWorldForward}");
}
/// <summary>
/// 로컬 축이 월드 축과 같은 방향인지 반대 방향인지 판단합니다.
/// 축 벡터를 인덱스로 변환합니다 (디버그용).
/// X축=1, Y축=2, Z축=3, 부호는 방향을 나타냄
/// </summary>
/// <param name="localAxis">로컬 축 방향 (월드 공간)</param>
/// <param name="worldAxis">비교할 월드 축</param>
/// <returns>같은 방향이면 1, 반대면 -1</returns>
private float GetAxisSign(Vector3 localAxis, Vector3 worldAxis)
private float GetAxisIndex(Vector3 axisVector)
{
// 내적으로 방향성 판단
float dot = Vector3.Dot(localAxis.normalized, worldAxis);
if (Mathf.Abs(axisVector.x) > 0.5f)
return 1f * Mathf.Sign(axisVector.x); // X축
else if (Mathf.Abs(axisVector.y) > 0.5f)
return 2f * Mathf.Sign(axisVector.y); // Y축
else
return 3f * Mathf.Sign(axisVector.z); // Z축
}
// 가장 지배적인 축 성분의 부호를 반환
if (Mathf.Abs(dot) > 0.5f) // 45도 이내면 해당 축으로 간주
/// <summary>
/// 세 로컬 축 중에서 목표 월드 방향과 가장 일치하는 축을 찾아 로컬 축 벡터를 반환합니다.
/// </summary>
/// <param name="localXInWorld">로컬 X축의 월드 방향</param>
/// <param name="localYInWorld">로컬 Y축의 월드 방향</param>
/// <param name="localZInWorld">로컬 Z축의 월드 방향</param>
/// <param name="worldDirection">비교할 월드 방향</param>
/// <param name="matchedAxisName">매칭된 축 이름 (출력용)</param>
/// <returns>해당 월드 방향을 담당하는 로컬 축 벡터 (부호 포함)</returns>
private Vector3 FindBestLocalAxisForWorld(Vector3 localXInWorld, Vector3 localYInWorld, Vector3 localZInWorld, Vector3 worldDirection, out string matchedAxisName)
{
float dotX = Vector3.Dot(localXInWorld, worldDirection);
float dotY = Vector3.Dot(localYInWorld, worldDirection);
float dotZ = Vector3.Dot(localZInWorld, worldDirection);
float absDotX = Mathf.Abs(dotX);
float absDotY = Mathf.Abs(dotY);
float absDotZ = Mathf.Abs(dotZ);
// 가장 큰 내적값을 가진 축이 해당 월드 방향과 가장 일치하는 축
if (absDotX >= absDotY && absDotX >= absDotZ)
{
return Mathf.Sign(dot);
matchedAxisName = dotX > 0 ? "+X (Right)" : "-X (Left)";
return Vector3.right * Mathf.Sign(dotX); // 로컬 X축 (부호 포함)
}
else if (absDotY >= absDotX && absDotY >= absDotZ)
{
matchedAxisName = dotY > 0 ? "+Y (Up)" : "-Y (Down)";
return Vector3.up * Mathf.Sign(dotY); // 로컬 Y축 (부호 포함)
}
else
{
matchedAxisName = dotZ > 0 ? "+Z (Forward)" : "-Z (Back)";
return Vector3.forward * Mathf.Sign(dotZ); // 로컬 Z축 (부호 포함)
}
// 축이 너무 비스듬하면 경고 (정상적인 휴머노이드 리그라면 발생 안함)
Debug.LogWarning($"[AxisNormalizer] 축이 비정상적으로 기울어져 있습니다: {localAxis} vs {worldAxis}");
return 1f;
}
/// <summary>
@ -415,6 +507,8 @@ namespace KindRetargeting
hipsOffsetZ = hipsOffsetZ,
kneeInOutWeight = kneeInOutWeight,
kneeFrontBackWeight = kneeFrontBackWeight,
footFrontBackOffset = footFrontBackOffset,
footInOutOffset = footInOutOffset,
floorHeight = floorHeight,
fingerCopyMode = fingerCopyMode,
useMotionFilter = useMotionFilter,
@ -473,6 +567,8 @@ namespace KindRetargeting
hipsOffsetZ = settings.hipsOffsetZ;
kneeInOutWeight = settings.kneeInOutWeight;
kneeFrontBackWeight = settings.kneeFrontBackWeight;
footFrontBackOffset = settings.footFrontBackOffset;
footInOutOffset = settings.footInOutOffset;
floorHeight = settings.floorHeight;
fingerCopyMode = settings.fingerCopyMode;
useMotionFilter = settings.useMotionFilter;
@ -572,10 +668,41 @@ namespace KindRetargeting
try
{
// 손가락 본들의 현재 로컬 회전을 저장 (I-포즈 적용 전)
// 손가락은 24~54번 본 (LeftThumbProximal ~ RightLittleDistal)
var savedFingerRotations = new Dictionary<HumanBodyBones, Quaternion>();
for (int i = 24; i <= 54; i++)
{
HumanBodyBones bone = (HumanBodyBones)i;
Transform fingerBone = targetAnimator.GetBoneTransform(bone);
if (fingerBone != null)
{
savedFingerRotations[bone] = fingerBone.localRotation;
}
}
// 타겟 아바타를 I-포즈로 설정 (몸체만 필요하지만 전체가 변경됨)
SetIPose(targetAnimator);
// 손가락 본들의 로컬 회전을 복원 (I-포즈 적용 후)
foreach (var kvp in savedFingerRotations)
{
Transform fingerBone = targetAnimator.GetBoneTransform(kvp.Key);
if (fingerBone != null)
{
fingerBone.localRotation = kvp.Value;
}
}
// 몸체 본들의 오프셋만 계산 (0~23번)
CalculateRotationOffsets(true);
// 손가락 본들의 오프셋 별도 계산 (24~54번)
// 손가락은 복원된 상태에서 오프셋 계산 (Rotation 모드용)
CalculateFingerRotationOffsets();
SaveSettings(); // 캘리브레이션 후 설정 저장
Debug.Log("I-포즈 캘리브레이션이 완료되었습니다.");
Debug.Log("I-포즈 캘리브레이션이 완료되었습니다. (손가락 포즈 유지)");
}
catch (System.Exception e)
{
@ -583,6 +710,38 @@ namespace KindRetargeting
}
}
/// <summary>
/// 손가락 본들의 회전 오프셋을 계산합니다.
/// I-포즈 캘리브레이션 시 손가락 포즈가 복원된 상태에서 호출되어야 합니다.
/// </summary>
private void CalculateFingerRotationOffsets()
{
if (sourceAnimator == null || targetAnimator == null)
return;
// 손가락 본들 (24~54)의 오프셋 계산
for (int i = 24; i <= 54; i++)
{
HumanBodyBones bone = (HumanBodyBones)i;
Transform sourceBone = sourceAnimator.GetBoneTransform(bone);
Transform targetBone = targetAnimator.GetBoneTransform(bone);
if (sourceBone != null && targetBone != null)
{
Quaternion offset = Quaternion.Inverse(sourceBone.rotation) * targetBone.rotation;
if (rotationOffsets.ContainsKey(bone))
{
rotationOffsets[bone] = offset;
}
else
{
rotationOffsets.Add(bone, offset);
}
}
}
}
private void InitializeIKJoints()
{
// IK 루트 찾기
@ -639,15 +798,25 @@ namespace KindRetargeting
}
/// <summary>
/// 머슬 데이터를 사용하여 손가락 포즈를 복제합니다.
/// SetHumanPose가 모든 본에 영향을 미치므로, 손가락을 제외한 모든 본의 Transform을 저장하고 복원합니다.
/// </summary>
private void CopyFingerPoseByMuscle()
{
Vector3 originalPosition = targetAnimator.GetBoneTransform(HumanBodyBones.Hips).position;
Quaternion originalRotation = targetAnimator.GetBoneTransform(HumanBodyBones.Hips).rotation;
if (sourcePoseHandler == null || targetPoseHandler == null)
return;
// 1. 손가락을 제외한 모든 본의 위치/회전 저장
savedBoneTransforms.Clear();
for (int i = 0; i < nonFingerBones.Length; i++)
{
Transform bone = targetAnimator.GetBoneTransform(nonFingerBones[i]);
if (bone != null)
{
savedBoneTransforms[nonFingerBones[i]] = (bone.position, bone.rotation);
}
}
// 2. 머슬 데이터 업데이트
sourcePoseHandler.GetHumanPose(ref sourcePose);
targetPoseHandler.GetHumanPose(ref targetPose);
@ -677,10 +846,18 @@ namespace KindRetargeting
targetPose.muscles[muscleIndex] = targetValue;
}
// 3. 머슬 포즈 적용 (손가락 포함 전체 본에 영향)
targetPoseHandler.SetHumanPose(ref targetPose);
targetAnimator.GetBoneTransform(HumanBodyBones.Hips).position = originalPosition;
targetAnimator.GetBoneTransform(HumanBodyBones.Hips).rotation = originalRotation;
// 4. 손가락을 제외한 모든 본의 위치/회전 복원
foreach (var kvp in savedBoneTransforms)
{
Transform bone = targetAnimator.GetBoneTransform(kvp.Key);
if (bone != null)
{
bone.SetPositionAndRotation(kvp.Value.position, kvp.Value.rotation);
}
}
}
private float ApplyFilter(float value, int fingerIndex)
@ -788,20 +965,33 @@ namespace KindRetargeting
targetHips.rotation = finalHipsRotation;
}
// 2. 로컬 오프셋 벡터 생성 (정규화 계수 적용)
Vector3 normalizedOffset = new Vector3(
hipsOffsetX * axisNormalizer.x * HipsWeightOffset, // 좌우
hipsOffsetY * axisNormalizer.y * HipsWeightOffset, // 상하
hipsOffsetZ * axisNormalizer.z * HipsWeightOffset // 앞뒤
);
// 2. 캐릭터 기준 로컬 오프셋 계산 (축 정규화 적용)
//
// 문제: 아바타마다 힙의 로컬 축 방향이 다름
// - 아바타 A: 로컬 Y가 "위", 로컬 Z가 "앞"
// - 아바타 B: 로컬 Z가 "위", 로컬 X가 "앞"
//
// 해결: T-포즈에서 계산한 축 매핑을 사용
// - localAxisForWorldRight: 실제로 "오른쪽"을 가리키는 로컬 축
// - localAxisForWorldUp: 실제로 "위"를 가리키는 로컬 축
// - localAxisForWorldForward: 실제로 "앞"을 가리키는 로컬 축
//
// 이렇게 하면 모든 아바타에서 동일하게 작동합니다.
// 3. 로컬 좌표계를 월드 좌표계로 변환
Vector3 worldOffset = targetHips.rotation * normalizedOffset;
// 힙의 현재 회전을 기준으로, 정규화된 방향 벡터 계산
Vector3 characterRight = finalHipsRotation * localAxisForWorldRight;
Vector3 characterUp = finalHipsRotation * localAxisForWorldUp;
Vector3 characterForward = finalHipsRotation * localAxisForWorldForward;
// 4. 힙 위치 동기화 + 로컬 오프셋 적용
Vector3 adjustedPosition = sourceHips.position + worldOffset;
Vector3 characterOffset =
characterRight * (hipsOffsetX * HipsWeightOffset) + // 캐릭터 기준 좌우
characterUp * (hipsOffsetY * HipsWeightOffset) + // 캐릭터 기준 상하
characterForward * (hipsOffsetZ * HipsWeightOffset); // 캐릭터 기준 앞뒤
// 5. 바닥 높이는 월드 Y축에 직접 적용 (중력 방향이므로 월드 기준)
// 3. 힙 위치 동기화 + 캐릭터 기준 오프셋 적용
Vector3 adjustedPosition = sourceHips.position + characterOffset;
// 4. 바닥 높이 추가 (월드 Y축 - 바닥은 항상 월드 기준)
adjustedPosition.y += floorHeight;
targetHips.position = adjustedPosition;
@ -951,7 +1141,7 @@ namespace KindRetargeting
}
/// <summary>
/// 손과 발끝 타겟의 위치와 회전을 업데이트합니다.
/// 손과 발끝 타겟의 위치와 회전을 업데이트합니다.
/// </summary>
/// <param name="endTarget">업데이트할 끝 타겟의 Transform</param>
/// <param name="endBone">대상 본</param>
@ -968,10 +1158,35 @@ namespace KindRetargeting
Vector3 targetPosition = sourceBone.position;
Quaternion targetRotation = targetBone.rotation;
// 발/발가락 본인 경우에만 바닥 높이 적용
// 발/발가락 본인 경우 오프셋 적용
if (endBone == HumanBodyBones.LeftToes || endBone == HumanBodyBones.RightToes)
{
// 바닥 높이 적용
targetPosition.y += floorHeight;
// 소스 아바타의 로컬 축 기준으로 발 오프셋 적용
// +Z: 앞으로, -Z: 뒤로
// 왼발: +X로 벌리기, -X로 모으기
// 오른발: -X로 벌리기, +X로 모으기 (반대)
Vector3 footOffset = Vector3.zero;
// 앞뒤 오프셋 (소스 아바타 기준 Z축)
footOffset += sourceAnimator.transform.forward * footFrontBackOffset;
// 안쪽/바깥쪽 오프셋 (소스 아바타 기준 X축)
// footInOutOffset > 0: 벌리기, < 0: 모으기
if (endBone == HumanBodyBones.LeftToes)
{
// 왼발: +일 때 왼쪽(+X)으로 벌림, -일 때 오른쪽(-X)으로 모음
footOffset += sourceAnimator.transform.right * footInOutOffset;
}
else // RightToes
{
// 오른발: +일 때 오른쪽(-X)으로 벌림, -일 때 왼쪽(+X)으로 모음
footOffset -= sourceAnimator.transform.right * footInOutOffset;
}
targetPosition += footOffset;
}
// 최종 위치와 회전 적용

View File

@ -15,6 +15,7 @@ namespace KindRetargeting
private bool showMotionFilterSettings = false;
private bool showRoughMotionSettings = false;
private bool showKneeSettings = true;
private bool showFootSettings = true;
private bool hasCachedData = false;
private bool showFloorSettings = false;
private bool showScaleSettings = true;
@ -35,6 +36,8 @@ namespace KindRetargeting
private SerializedProperty fingerRoughnessProp;
private SerializedProperty kneeInOutWeightProp;
private SerializedProperty kneeFrontBackWeightProp;
private SerializedProperty footFrontBackOffsetProp;
private SerializedProperty footInOutOffsetProp;
private SerializedProperty floorHeightProp;
private SerializedProperty avatarScaleProp;
@ -57,6 +60,8 @@ namespace KindRetargeting
fingerRoughnessProp = serializedObject.FindProperty("fingerRoughness");
kneeInOutWeightProp = serializedObject.FindProperty("kneeInOutWeight");
kneeFrontBackWeightProp = serializedObject.FindProperty("kneeFrontBackWeight");
footFrontBackOffsetProp = serializedObject.FindProperty("footFrontBackOffset");
footInOutOffsetProp = serializedObject.FindProperty("footInOutOffset");
floorHeightProp = serializedObject.FindProperty("floorHeight");
avatarScaleProp = serializedObject.FindProperty("avatarScale");
}
@ -97,24 +102,46 @@ namespace KindRetargeting
{
EditorGUI.indentLevel++;
// 축 정규화 정보 표시
// 축 매핑 정보 표시
if (debugAxisNormalizerProp != null)
{
Vector3 normalizer = debugAxisNormalizerProp.vector3Value;
Vector3 axisMapping = debugAxisNormalizerProp.vector3Value;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUILayout.LabelField("축 정규화 정보", EditorStyles.boldLabel);
EditorGUILayout.LabelField("축 매핑 정보 (T-포즈 기준)", EditorStyles.boldLabel);
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.Vector3Field("정규화 계수", normalizer);
EditorGUI.EndDisabledGroup();
// 플레이 모드에서만 정확한 정보 표시
if (Application.isPlaying && axisMapping != Vector3.one)
{
// axisMapping: 1=X, 2=Y, 3=Z, 부호는 방향
string GetAxisName(float value)
{
int axis = Mathf.RoundToInt(Mathf.Abs(value));
string sign = value > 0 ? "+" : "-";
return axis switch
{
1 => $"{sign}X",
2 => $"{sign}Y",
3 => $"{sign}Z",
_ => "?"
};
}
EditorGUILayout.HelpBox(
$"X축: {(normalizer.x > 0 ? " " : " ")}\n" +
$"Y축: {(normalizer.y > 0 ? " " : " ")}\n" +
$"Z축: {(normalizer.z > 0 ? " " : " ")}\n\n" +
"이 계수는 Start()에서 자동 계산되며, 항상 직관적인 방향으로 제어할 수 있게 합니다.",
MessageType.Info);
EditorGUILayout.HelpBox(
"T-포즈에서 분석된 축 매핑:\n" +
$" 좌우 오프셋 → 로컬 {GetAxisName(axisMapping.x)} 축\n" +
$" 상하 오프셋 → 로컬 {GetAxisName(axisMapping.y)} 축\n" +
$" 앞뒤 오프셋 → 로컬 {GetAxisName(axisMapping.z)} 축\n\n" +
"이 매핑 덕분에 모든 아바타에서 동일하게 작동합니다.",
MessageType.Info);
}
else
{
EditorGUILayout.HelpBox(
"플레이 모드에서 T-포즈 분석 후 축 매핑 정보가 표시됩니다.\n" +
"이 매핑은 각 아바타의 힙 로컬 축 방향에 맞춰 자동 계산됩니다.",
MessageType.Info);
}
EditorGUILayout.EndVertical();
GUILayout.Space(5);
@ -142,7 +169,7 @@ namespace KindRetargeting
{
EditorGUI.indentLevel++;
// 몸릎 안/밖 정만 표시
// 무릎 안/밖 조정
EditorGUILayout.Slider(kneeFrontBackWeightProp, -1f, 1f,
new GUIContent("무릎 앞/뒤 가중치", "음수: 뒤로, 양수: 앞으로"));
EditorGUILayout.Slider(kneeInOutWeightProp, -1f, 1f,
@ -153,6 +180,22 @@ namespace KindRetargeting
GUILayout.Space(5);
// 발 IK 위치 조정 Foldout
showFootSettings = EditorGUILayout.Foldout(showFootSettings, "발 IK 위치 조정", true);
if (showFootSettings)
{
EditorGUI.indentLevel++;
EditorGUILayout.Slider(footFrontBackOffsetProp, -1f, 1f,
new GUIContent("발 앞/뒤 오프셋", "+: 앞으로, -: 뒤로"));
EditorGUILayout.Slider(footInOutOffsetProp, -1f, 1f,
new GUIContent("발 벌리기/모으기", "+: 벌리기, -: 모으기"));
EditorGUI.indentLevel--;
}
GUILayout.Space(5);
// 손가락 복제 설정 Foldout
showFingerCopySettings = EditorGUILayout.Foldout(showFingerCopySettings, "손가락 복제 설정");
if (showFingerCopySettings)

View File

@ -21,6 +21,7 @@ public class RetargetingControlWindow : EditorWindow
private Dictionary<int, bool> motionSettingsFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> floorSettingsFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> scaleSettingsFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> footSettingsFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> leftHandFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> rightHandFoldouts = new Dictionary<int, bool>();
private Dictionary<int, bool> headFoldouts = new Dictionary<int, bool>();
@ -226,6 +227,7 @@ public class RetargetingControlWindow : EditorWindow
if (!motionSettingsFoldouts.ContainsKey(instanceID)) motionSettingsFoldouts[instanceID] = false;
if (!floorSettingsFoldouts.ContainsKey(instanceID)) floorSettingsFoldouts[instanceID] = false;
if (!scaleSettingsFoldouts.ContainsKey(instanceID)) scaleSettingsFoldouts[instanceID] = false;
if (!footSettingsFoldouts.ContainsKey(instanceID)) footSettingsFoldouts[instanceID] = true;
if (!leftHandFoldouts.ContainsKey(instanceID)) leftHandFoldouts[instanceID] = false;
if (!rightHandFoldouts.ContainsKey(instanceID)) rightHandFoldouts[instanceID] = false;
if (!headFoldouts.ContainsKey(instanceID)) headFoldouts[instanceID] = false;
@ -264,18 +266,23 @@ public class RetargetingControlWindow : EditorWindow
var hipsOffsetYProp = serializedObject.FindProperty("hipsOffsetY");
var hipsOffsetZProp = serializedObject.FindProperty("hipsOffsetZ");
// 정규화 계수 표시
// 축 매핑 정보 표시
var normalizerProp = serializedObject.FindProperty("debugAxisNormalizer");
if (normalizerProp != null)
if (normalizerProp != null && Application.isPlaying)
{
Vector3 norm = normalizerProp.vector3Value;
if (norm != Vector3.zero) // 초기화되었을 때만 표시
Vector3 mapping = normalizerProp.vector3Value;
if (mapping != Vector3.one) // 초기화되었을 때만 표시
{
string xIcon = norm.x > 0 ? "↔" : "↔(반전)";
string yIcon = norm.y > 0 ? "↕" : "↕(반전)";
string zIcon = norm.z > 0 ? "⇄" : "⇄(반전)";
// mapping: 1=X, 2=Y, 3=Z, 부호는 방향
string GetAxis(float v) => Mathf.RoundToInt(Mathf.Abs(v)) switch
{
1 => v > 0 ? "+X" : "-X",
2 => v > 0 ? "+Y" : "-Y",
3 => v > 0 ? "+Z" : "-Z",
_ => "?"
};
EditorGUILayout.LabelField($"축 상태: X{xIcon} Y{yIcon} Z{zIcon}",
EditorGUILayout.LabelField($"축 매핑: 좌우→{GetAxis(mapping.x)} 상하→{GetAxis(mapping.y)} 앞뒤→{GetAxis(mapping.z)}",
EditorStyles.miniLabel);
}
}
@ -303,6 +310,19 @@ public class RetargetingControlWindow : EditorWindow
EditorGUI.indentLevel--;
}
// 발 IK 위치 조정
footSettingsFoldouts[instanceID] = EditorGUILayout.Foldout(footSettingsFoldouts[instanceID], "발 IK 위치 조정", true);
if (footSettingsFoldouts[instanceID])
{
EditorGUI.indentLevel++;
var footFrontBackProp = serializedObject.FindProperty("footFrontBackOffset");
var footInOutProp = serializedObject.FindProperty("footInOutOffset");
EditorGUILayout.Slider(footFrontBackProp, -1f, 1f, new GUIContent("발 앞/뒤 오프셋", "+: 앞으로, -: 뒤로"));
EditorGUILayout.Slider(footInOutProp, -1f, 1f, new GUIContent("발 벌리기/모으기", "+: 벌리기, -: 모으기"));
EditorGUI.indentLevel--;
}
// 손가락 제어 설정
fingerControlFoldouts[instanceID] = EditorGUILayout.Foldout(fingerControlFoldouts[instanceID], "손가락 제어 설정", true);
if (fingerControlFoldouts[instanceID])

View File

@ -1,348 +0,0 @@
////======================================================================================================
//// Copyright 2023, NaturalPoint Inc.
////======================================================================================================
/**
* ExampleGloveAdapterSingleton class is an adapter class provided to demonstrate how communication between plugin device and
* the glove SDK can be managed. A singleton instance of this class manages interaction between plugin device and the glove
* device SDK. The adapter instance also stores a keeps the latest data and device info map that stores the currently detected device serials
* and the latest frame data so that corresponding glove device can poll from it. Please note that this is provided only as an example, and
* there could be other ways to set this up.
*/
#pragma once
#include <list>
#include <mutex>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <functional>
// OptiTrack Peripheral Device API
#include "AnalogChannelDescriptor.h"
#include "GloveDataFormat.h"
#include "HardwareSimulator.h"
// Rokoko Integration
#include "RokokoData.h"
#include "RokokoUDPReceiver.h"
#include "RokokoDataParser.h"
#include "RokokoDataConverter.h"
namespace OptiTrackPluginDevices
{
namespace ExampleDevice
{
class ExampleGloveAdapterSingleton;
static ExampleGloveAdapterSingleton* s_Instance = nullptr;
static std::unique_ptr<ExampleGloveAdapterSingleton> gGloveAdapter;
/**
* This is an example glove adapter (singleton) class provided to demonstrate how glove data can be populated.
* This adapter class is reponsible for all interaction with the device SDK, and populating the glove data.
* Glove data for multiple glove devices should get aggregated in here.
*/
class ExampleGloveAdapterSingleton
{
friend class ExampleGloveDevice;
public:
ExampleGloveAdapterSingleton(AnalogSystem::IDeviceManager* pDeviceManager);
~ExampleGloveAdapterSingleton();
// Singleton design pattern
ExampleGloveAdapterSingleton(const ExampleGloveAdapterSingleton&) = delete; // Should not be cloneable
ExampleGloveAdapterSingleton& operator=(const ExampleGloveAdapterSingleton& other) = delete; // Shounot be assignable
/**
* Should call the shutdown from the plugin SDK. In this case, shutsdown the simulator
*/
bool ClientShutdown();
/**
* Detection thread for connecting to the glove server.
*/
void DoDetectionThread();
std::thread mDetectionThread;
unsigned int mConnectionAttemptCount = 0;
const unsigned int kMaxConnectionAttempt = 10;
/**
* Connect to the glove host.
*/
bool ConnectToHost();
/**
* Connect to Rokoko Studio via UDP.
*/
bool ConnectToRokoko();
/**
* Disconnect from Rokoko Studio.
*/
void DisconnectFromRokoko();
private:
/**
* Returns whether detector is connected to Glove Host.
*/
bool IsConnected();
/**
* Saves the latest data to the map
*/
void SetLatestData(const sGloveDeviceData& gloveFingerData);
/**
* Pointer to device manager for additional operations
*/
void SetDeviceManager(AnalogSystem::IDeviceManager* pDeviceManager);
/**
* Saves the latest glove data to the map
*/
void SetLatestDeviceInfo(const sGloveDeviceBaseInfo& deviceInfo);
/**
* Gets the latest data for device with given unique serial
*/
bool GetLatestData(const std::uint64_t mDeviceSerial, sGloveDeviceData& gloveFingerData);
/**
* Creates new device by instantiating the factory and transferring it to Motive
*/
void CreateNewGloveDevice(sGloveDeviceBaseInfo& deviceInfo);
/**
* Prints error into Motive.
*/
void NotifyConnectionFail();
bool bIsConnected = false;
bool bIsDetecting = true;
int mCurrentDeviceIndex = 0;
std::string mServerAddress = "";
/**
* [Glove SDK Placeholder]
* Example data map for storing aggregated device data.
*/
uint16_t mDeviceCount = 0;
std::vector<uint64_t> mDetectedDevices;
std::unordered_map<uint64_t, sGloveDeviceData> mLatestGloveData;
std::unordered_map<uint64_t, sGloveDeviceBaseInfo> mLatestDeviceInfo;
// T-포즈 캘리브레이션 데이터 (로컬 로테이션 계산을 위해 필요)
std::unordered_map<uint64_t, std::vector<sFingerNode>> mTPoseReferences; // 장치별 T-포즈 기준값
std::unordered_map<uint64_t, bool> mTPoseCalibrated; // 장치별 캘리브레이션 상태
/**
* Rokoko integration members
*/
std::unique_ptr<RokokoIntegration::RokokoUDPReceiver> mRokokoReceiver;
bool bIsRokokoConnected = false;
RokokoData::LiveFrame_v4 mLastRokokoFrame;
/**
* [Legacy Glove SDK Placeholder - Commented Out]
* The following methods were sample callback functions for simulated hardware.
* Now replaced by Rokoko UDP communication.
*/
// bool bIsSimulating;
void StartSimulatedHardware(int deviceCount); // Legacy support
static void RegisterSDKCallbacks(); // Legacy support
static void OnDataCallback(std::vector<SimulatedPluginDevices::SimulatedGloveFrameData>& gloveFingerData); // Legacy support
static void OnDeviceInfoCallback(std::vector<SimulatedPluginDevices::SimulatedDeviceInfo>& newGloveInfo); // Legacy support
static sGloveDeviceBaseInfo ConvertDeviceInfoFormat(SimulatedPluginDevices::SimulatedDeviceInfo& glove); // Legacy support
static sGloveDeviceData ConvertDataFormat(const SimulatedPluginDevices::SimulatedGloveFrameData& glove); // Legacy support
/**
* Rokoko UDP data callback function.
*/
void OnRokokoDataReceived(const std::vector<uint8_t>& data, const std::string& senderIP);
/**
* Process received Rokoko data and convert to OptiTrack format.
*/
void ProcessRokokoData(const std::vector<uint8_t>& data);
/**
* Update device information (battery, signal strength, etc.)
*/
void UpdateDeviceInfo(uint64_t deviceId);
// Dynamic Device Detection and Management
void DetectAndCreateRokokoDevices();
void DetectActorsFromRokokoData(const RokokoData::LiveFrame_v4& rokokoFrame);
void ProcessMultipleDeviceData(const RokokoData::LiveFrame_v4& rokokoFrame);
/**
* Process hand data for a specific device
*/
bool ProcessHandData(const RokokoData::Body& body, uint64_t deviceId, eGloveHandSide handSide);
/**
* Map left hand joints from Rokoko data
*/
void MapLeftHandJoints(const RokokoData::Body& body, std::vector<sFingerNode>& nodes);
/**
* Map right hand joints from Rokoko data
*/
void MapRightHandJoints(const RokokoData::Body& body, std::vector<sFingerNode>& nodes);
/**
* Map individual joint data
*/
void MapJoint(const RokokoData::ActorJointFrame& rokokoJoint, sFingerNode& optiTrackNode);
// 로컬 로테이션 변환 함수들
void ConvertToLocalRotations(std::vector<sFingerNode>& nodes, eGloveHandSide handSide);
void ApplyLocalRotation(sFingerNode& childNode, const sFingerNode& parentNode);
// 쿼터니언 연산 헬퍼 함수들
void MultiplyQuaternions(const sFingerNode& q1, const sFingerNode& q2, sFingerNode& result);
void InverseQuaternion(const sFingerNode& q, sFingerNode& result);
void NormalizeQuaternion(sFingerNode& q);
// T-포즈 캘리브레이션 시스템
void CalibrateTPose(uint64_t deviceId, const std::vector<sFingerNode>& tPoseData);
void ApplyTPoseOffset(std::vector<sFingerNode>& nodes, uint64_t deviceId);
bool IsTPoseCalibrated(uint64_t deviceId) const;
void ResetTPoseCalibration(uint64_t deviceId);
// 손목 기준 로컬 변환 시스템 (기존)
void ConvertToWristLocalRotations(std::vector<sFingerNode>& nodes, const RokokoData::Body& body, eGloveHandSide handSide);
bool GetWristRotation(const RokokoData::Body& body, eGloveHandSide handSide, sFingerNode& wristRotation);
// 진짜 로컬 로테이션 변환 시스템 (계층적)
void ConvertToTrueLocalRotations(std::vector<sFingerNode>& nodes, const RokokoData::Body& body, eGloveHandSide handSide);
void CalculateFingerLocalRotations(const std::vector<RokokoData::ActorJointFrame*>& fingerJoints, std::vector<sFingerNode>& outputNodes, int startIndex, const RokokoData::Body& body, eGloveHandSide handSide);
bool GetFingerJointRotations(const RokokoData::Body& body, eGloveHandSide handSide, std::vector<std::vector<RokokoData::ActorJointFrame*>>& allFingers);
// 좌표계 변환 및 디버깅
void ConvertRokokoToOptiTrackCoordinates(sFingerNode& node, eGloveHandSide handSide);
void LogRotationData(const std::string& label, const sFingerNode& rotation);
void DebugCoordinateSystem(const RokokoData::Body& body, eGloveHandSide handSide);
// 절대 로컬 로테이션 시스템 (손목에 완전히 독립적)
void ConvertToAbsoluteLocalRotations(std::vector<sFingerNode>& nodes, const RokokoData::Body& body, eGloveHandSide handSide);
void CalculateAbsoluteLocalForFinger(const std::vector<RokokoData::ActorJointFrame*>& fingerJoints, std::vector<sFingerNode>& outputNodes, int startIndex, eGloveHandSide handSide);
sFingerNode CalculateRelativeRotation(const sFingerNode& parent, const sFingerNode& child);
// Unity 방식 Rokoko 데이터 처리 (원시 데이터 + T-포즈 오프셋)
void ConvertToUnityRokokoMethod(std::vector<sFingerNode>& nodes, const RokokoData::Body& body, eGloveHandSide handSide);
sFingerNode GetUnityTPoseOffset(int fingerIndex, int jointIndex, eGloveHandSide handSide);
void ApplyUnityRokokoRotation(sFingerNode& node, const RokokoData::ActorJointFrame* jointFrame, int fingerIndex, int jointIndex, eGloveHandSide handSide);
// 가상 Unity 아바타 시뮬레이션 시스템
void ConvertToVirtualUnityAvatar(std::vector<sFingerNode>& nodes, const RokokoData::Body& body, eGloveHandSide handSide);
// Unity Transform 시뮬레이션 구조
struct VirtualTransform {
sFingerNode localRotation; // Unity localRotation
sFingerNode worldRotation; // Unity rotation (world)
VirtualTransform* parent; // Unity parent transform
std::vector<VirtualTransform*> children; // Unity children
std::string name; // 디버깅용
};
struct VirtualUnityAvatar {
// 전체 스켈레톤 구조 (Unity Humanoid와 동일한 계층)
VirtualTransform root;
// 몸통 구조
VirtualTransform* hips; // 허리 (Root)
VirtualTransform* spine; // 스파인
VirtualTransform* chest; // 가슴
// 어깨 구조
VirtualTransform* leftShoulder; // 왼쪽 어깨
VirtualTransform* rightShoulder; // 오른쪽 어깨
// 팔 구조
VirtualTransform* leftUpperArm; // 왼쪽 상완
VirtualTransform* leftLowerArm; // 왼쪽 하완
VirtualTransform* leftHand; // 왼쪽 손
VirtualTransform* rightUpperArm; // 오른쪽 상완
VirtualTransform* rightLowerArm; // 오른쪽 하완
VirtualTransform* rightHand; // 오른쪽 손
// 손가락 구조 (Unity 계층과 동일)
VirtualTransform* leftThumb[3]; // Proximal, Intermediate, Distal
VirtualTransform* leftIndex[3];
VirtualTransform* leftMiddle[3];
VirtualTransform* leftRing[3];
VirtualTransform* leftLittle[3];
VirtualTransform* rightThumb[3];
VirtualTransform* rightIndex[3];
VirtualTransform* rightMiddle[3];
VirtualTransform* rightRing[3];
VirtualTransform* rightLittle[3];
};
// 가상 Unity 아바타 헬퍼 함수들
void InitializeVirtualUnityAvatar(VirtualUnityAvatar& avatar);
void ApplyRokokoDataToVirtualAvatar(VirtualUnityAvatar& avatar, const RokokoData::Body& body);
void CalculateLocalRotationsFromWorldRotations(VirtualUnityAvatar& avatar);
void ExtractLocalRotationsFromVirtualAvatar(const VirtualUnityAvatar& avatar, std::vector<sFingerNode>& nodes, eGloveHandSide handSide);
void UpdateWorldRotationFromParent(VirtualTransform* transform);
// 가상 손 노드 구조
struct VirtualJoint {
sFingerNode worldRotation;
sFingerNode localRotation;
VirtualJoint* parent;
};
struct VirtualFinger {
VirtualJoint mp; // Metacarpophalangeal
VirtualJoint pip; // Proximal Interphalangeal
VirtualJoint dip; // Distal Interphalangeal
};
struct VirtualHand {
sFingerNode wristRotation;
VirtualFinger thumb;
VirtualFinger index;
VirtualFinger middle;
VirtualFinger ring;
VirtualFinger little;
};
// 가상 손 구조 헬퍼 함수들
void BuildVirtualHandFromRokoko(VirtualHand& virtualHand, const RokokoData::Body& body, eGloveHandSide handSide);
void CalculateHierarchicalLocalRotations(VirtualHand& virtualHand);
void ExtractLocalRotationsToNodes(const VirtualHand& virtualHand, std::vector<sFingerNode>& nodes);
sFingerNode CalculateLocalRotationFromParent(const VirtualJoint& parent, const VirtualJoint& child);
protected:
/**
* [Legacy Glove SDK Simulator - Commented Out]
* Instance of simulator (now replaced by Rokoko integration)
*/
// SimulatedPluginDevices::HardwareSimulator* mGloveSimulator;
/**
* [Glove SDK Placeholder]
* Example glove data mutex
*/
std::recursive_mutex* mGloveDataMutex;
/**
* Pointer to device manager in Motive for reporting error messages.
*/
AnalogSystem::IDeviceManager* mDeviceManager;
};
}
}

Binary file not shown.
1 version https://git-lfs.github.com/spec/v1
2 oid sha256:816498d40aca6a7060d48313bd1946b20553894715095670b14192d4639bdce5
3 size 549783

View File

@ -1,311 +0,0 @@
//======================================================================================================
// Copyright 2022, NaturalPoint Inc.
//======================================================================================================
#pragma once
#include "ExampleGloveDevice.h"
#include "ExampleGloveAdapterSingleton.h"
// OptiTrack Peripheral Device API
#include "AnalogChannelDescriptor.h"
#include "IDeviceManager.h"
using namespace AnalogSystem;
using namespace OptiTrackPluginDevices;
using namespace GloveDeviceProperties;
using namespace ExampleDevice;
///////////////////////////////////////////////////////////////////////////////
//
// Device Helper: Initialization and Shutdown
//
void OptiTrackPluginDevices::ExampleDevice::ExampleGlove_EnumerateDeviceFactories(IDeviceManager* pDeviceManager, std::list<std::unique_ptr<IDeviceFactory>>& dfs)
{
// Start server detection
if (gGloveAdapter == nullptr) {
gGloveAdapter = std::make_unique<ExampleGloveAdapterSingleton>(pDeviceManager);
}
}
void OptiTrackPluginDevices::ExampleDevice::ExampleGlove_Shutdown()
{
if (gGloveAdapter != nullptr)
{
gGloveAdapter->ClientShutdown();
gGloveAdapter.reset();
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Example Glove Device Factory
//
const char* OptiTrackPluginDevices::ExampleDevice::ExampleGloveDeviceFactory::Name() const
{
return "ExampleGloveDevice";
}
std::unique_ptr<AnalogSystem::IDevice> OptiTrackPluginDevices::ExampleDevice::ExampleGloveDeviceFactory::Create() const
{
ExampleGloveDevice* pDevice = new ExampleGloveDevice(mDeviceSerial, mDeviceInfo);
SetCommonGloveDeviceProperties(pDevice);
SetQuaternionDataChannels(pDevice);
// Transfer ownership to host
std::unique_ptr<AnalogSystem::IDevice> ptrDevice(pDevice);
return ptrDevice;
}
///////////////////////////////////////////////////////////////////////////////
//
// Example Glove Device
//
OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::ExampleGloveDevice(uint32_t serial, sGloveDeviceBaseInfo deviceInfo)
{
mDeviceInfo = deviceInfo;
mDeviceSerial = deviceInfo.gloveId;
bIsEnabled = true;
}
bool OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::Configure()
{
bool success = Deconfigure();
if (!success)
return false;
// update device's buffer allocation based on current channel and data type configuration
success = cPluginDevice::Configure();
if (!success)
return false;
bIsConfigured = success;
DeviceManager()->MessageToHost(this, "", MessageType_RequestRestart);
return success;
}
bool OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::Deconfigure()
{
bool success = cPluginDevice::Deconfigure();
return success;
}
bool OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::StartCapture()
{
bool success = cPluginDevice::StartCapture();
bIsCollecting = true;
mCollectionThread = CreateThread(nullptr, 0, CollectionThread, this, 0, nullptr);
if (mCollectionThread == nullptr)
{
return false;
bIsCollecting = false;
}
return success;
}
bool OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::StopCapture()
{
bool success = cPluginDevice::StopCapture();
// REQUIRED: Stop collecting data. Terminate hardware device polling thread
bIsCollecting = false;
DWORD waitResult = WaitForSingleObject(mCollectionThread, 1000);
if (waitResult == WAIT_OBJECT_0)
{
CloseHandle(mCollectionThread);
mCollectionThread = NULL;
success = true;
}
else if (waitResult == WAIT_TIMEOUT)
{
BOOL result = TerminateThread(mCollectionThread, 0);
success = (result == TRUE);
}
else
{
success = false;
}
return success;
}
void OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::OnPropertyChanged(const char* propertyName)
{
cPluginDevice::OnPropertyChanged(propertyName);
if (strcmp(propertyName, kEnabledPropName) == 0)
{
// Update device enabled state
GetProperty(kEnabledPropName, bIsEnabled);
}
else if (strcmp(propertyName, kRatePropName) == 0)
{
// Update device capture rate
GetProperty(kRatePropName, mDeviceRateFPS);
mRequestedRateMS = (1.0f / mDeviceRateFPS) * 1000.0f;
}
else if (strcmp(propertyName, kDataStatePropName) == 0)
{
int deviceState = 0;
GetProperty(kDataStatePropName, deviceState);
if (deviceState != DeviceDataState::DeviceState_ReceivingData)
{
// if not receiving data, disable battery state and signal strength
mBatteryLevel = GloveDeviceProp_BatteryUninitialized;
SetProperty(GloveDeviceProp_Battery, mBatteryLevel);
mSignalStrength = GloveDeviceProp_SignalStrengthUnitialized;
SetProperty(GloveDeviceProp_SignalStrength, mSignalStrength);
}
}
else if (strcmp(propertyName, GloveDeviceProp_Solver) == 0)
{
// Route solver type to device user data for interpreting in pipeline
int solver = 0;
GetProperty(GloveDeviceProp_Solver, solver);
SetProperty(cPluginDeviceBase::kUserDataPropName, solver);
}
}
unsigned long __stdcall OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::CollectionThread(LPVOID Context)
{
ExampleGloveDevice* pThis = static_cast<ExampleGloveDevice*>(Context);
return pThis->DoCollectionThread();
}
unsigned long OptiTrackPluginDevices::ExampleDevice::ExampleGloveDevice::DoCollectionThread()
{
/* Collection Thread -
Motive's 15 channel glove data channel format for finger node rotations:
1 = Thumb MP 1 (w,x,y,z)
2 = Thumb PIP 2
3 = Thumb DIP 3
4 = Index MP 1
5 = Index PIP 2
6 = Index DIP 3
7 = Middle MP 1
8 = Middle PIP 2
9 = Middle DIP 3
10 = Ring MP 1
11 = Ring PIP 2
12 = Ring DIP 3
13 = Pinky MP 1
14 = Pinky PIP 2
15 = Pinky DIP 3
Hand joint orientation respects right-handed coordinate system.
For left hand, +X is pointed towards the finger tip.
For right hand, +X is pointer towards the wrist or the body.
*/
// timers used for frame and ui updates
std::chrono::high_resolution_clock::time_point frameTimerStart, frameTimerEnd;
std::chrono::high_resolution_clock::time_point uiTimerStart, uiTimerEnd;
std::chrono::milliseconds actualFrameDurationMS;
double adjustment = 0.0;
double durationDeltaMS = 0.0;
// Glove device parameters (rate / battery / signal)
GetProperty(kEnabledPropName, bIsEnabled);
GetProperty(GloveDeviceProp_Battery, mBatteryLevel);
GetProperty(GloveDeviceProp_SignalStrength, mSignalStrength);
GetProperty(kRatePropName, mDeviceRateFPS);
mRequestedRateMS = (1.0f / mDeviceRateFPS) * 1000.0f;
// Initialize glove handedness
InitializeGloveProperty();
//glove channel data arrray to be copied
float gloveChannelData[kGloveAnalogChannelCount];
// Collection thread
uiTimerStart = std::chrono::high_resolution_clock::now();
while (bIsCollecting)
{
frameTimerStart = std::chrono::high_resolution_clock::now();
int deviceFrameID = this->FrameCounter();
// Skip disabled devices
bool isDeviceEnabled = false;
GetProperty(kEnabledPropName, isDeviceEnabled);
if (!isDeviceEnabled) continue;
// Poll latest glove data from the adapter
sGloveDeviceData t_data;
bool isGloveDataAvailable = gGloveAdapter->GetLatestData(mDeviceInfo.gloveId, t_data);
if (isGloveDataAvailable)
{
if (!bIsInitialized) {
InitializeGloveProperty();
}
// Update ui every 5 secs (too frequent can cause unnecessary slowdowns)
uiTimerEnd = std::chrono::high_resolution_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(uiTimerEnd - uiTimerStart);
if (elapsedTime.count() > 5)
{
UpdateGloveProperty(mDeviceInfo);
uiTimerStart = std::chrono::high_resolution_clock::now();
}
// Frame Begin: get frame from device buffer
AnalogFrame<float>* pFrame = this->BeginFrameUpdate(deviceFrameID);
if (pFrame)
{
// fill in frame header
int flags = 0;
// Iterate through each bone and populate channel data.
// Skip the first bone, hand base, as it's driven from rigid body transform instead.
for (int i = 0; i < 15; i++)
{
int nodeChannelIndex = i * 4;
gloveChannelData[nodeChannelIndex] = t_data.nodes.at(i).quat_w; //w
gloveChannelData[nodeChannelIndex + 1] = t_data.nodes.at(i).quat_x; //x
gloveChannelData[nodeChannelIndex + 2] = t_data.nodes.at(i).quat_y; //y
gloveChannelData[nodeChannelIndex + 3] = t_data.nodes.at(i).quat_z; //z
}
pFrame->SetID(deviceFrameID);
pFrame->SetFlag(flags);
//pFrame->SetTimestamp((double)mLastGloveDataTimebstamp.time);
::memcpy(pFrame->ChannelData(), &gloveChannelData[0], kGloveAnalogChannelCount * sizeof(float));
EndFrameUpdate();
this->SetFrameCounter(deviceFrameID + 1);
}
// End frame update. Sleep the thread for the remaining frame period.
std::this_thread::sleep_for(std::chrono::milliseconds((int)(mRequestedRateMS - adjustment)));
frameTimerEnd = std::chrono::high_resolution_clock::now();
actualFrameDurationMS = std::chrono::duration_cast<std::chrono::milliseconds>(frameTimerEnd - frameTimerStart);
durationDeltaMS = actualFrameDurationMS.count() - mRequestedRateMS;
// estimating adjustment to prevent oscillation on sleep duration.
if (durationDeltaMS > 1.0)
adjustment = -1.0;
else if (durationDeltaMS > 2.0)
adjustment = -2.0;
else if (durationDeltaMS > 3.0)
adjustment = -3.0;
else if (durationDeltaMS < -3.0)
adjustment = -3.0;
else if (durationDeltaMS < -2.0)
adjustment = 2.0;
else if (durationDeltaMS < -1.0)
adjustment = 1.0;
else
adjustment = 0.0;
if (fabs(adjustment) > 1.0)
{
this->LogError(MessageType_StatusInfo, "[Example Device] Device timing resolution off by %3.1f ms (requested:%3.1f, actual:%3.1f)", durationDeltaMS, mRequestedRateMS, (double) actualFrameDurationMS.count());
}
}
}
return 0;
}

View File

@ -1,86 +0,0 @@
//======================================================================================================
// Copyright 2023, NaturalPoint Inc.
//======================================================================================================
/**
* This is an example glove device provided to demonstrate how a plugin device can be set up as a glove device
* in Motive. This class derives from GloveDeviceBase class which contains basic setups required by gloves.
*/
#pragma once
#include <memory>
#include <list>
// OptiTrack Peripheral Device API
#include "dllcommon.h"
#include "GloveDeviceBase.h"
#include "GloveDataFormat.h"
#include "ExampleGloveAdapterSingleton.h"
namespace OptiTrackPluginDevices
{
namespace ExampleDevice{
class ExampleGloveDevice;
class ExampleGloveDeviceFactory;
void ExampleGlove_EnumerateDeviceFactories(AnalogSystem::IDeviceManager* pDeviceManager, std::list<std::unique_ptr<AnalogSystem::IDeviceFactory>>& dfs);
void ExampleGlove_Shutdown();
/**
* For creating a device in Motive, a factory class must be created first. This example class inherits from the
* parent glove device factory where common glove functionalities and configurations are set.
*/
class ExampleGloveDeviceFactory : public OptiTrackPluginDevices::GloveDeviceFactoryBase
{
public:
ExampleGloveDeviceFactory(std::string deviceName, sGloveDeviceBaseInfo deviceInfo) :
GloveDeviceFactoryBase(deviceName.c_str(), deviceInfo.gloveId), mDeviceInfo(deviceInfo)
{
}
/**
* Return device factory name
*/
virtual const char* Name() const override;
/**
* The following method gets called by Motive. It creates and returns a new instance of device and transfers ownership to Motive.
*/
std::unique_ptr<AnalogSystem::IDevice> Create() const override;
private:
sGloveDeviceBaseInfo mDeviceInfo;
};
/**
* ExampleGloveDevice inherits from GloveDeviceBase and demonstrates how a glove plugin device can be created.
* Each device gets their own collection thread where they populate the channel data. This class is inherited from the parent
* GloveDeviceBase class where the basic glove setup is shown.
*/
class ExampleGloveDevice : public OptiTrackPluginDevices::GloveDeviceBase
{
public:
ExampleGloveDevice(uint32_t serial, sGloveDeviceBaseInfo deviceInfo);
virtual ~ExampleGloveDevice() = default;
// IDevice implementation
virtual bool Configure();
virtual bool Deconfigure();
virtual bool StartCapture();
virtual bool StopCapture();
virtual void OnPropertyChanged(const char* propertyName);
private:
/**
* Collection thread for populating glove analog data channels
*/
static unsigned long __stdcall CollectionThread(LPVOID Context);
unsigned long DoCollectionThread() override;
void* mCollectionThread = nullptr;
};
}
}

Binary file not shown.

View File

@ -1,84 +0,0 @@
//======================================================================================================
// Copyright 2023, NaturalPoint Inc.
//======================================================================================================
/**
* This includes common glove data formats referenced in Motive.
*/
#pragma once
#include <list>
#include <mutex>
#include <vector>
#include <set>
enum class eGloveHandSide : int
{
Unknown = 0,
Left = 1,
Right = 2
};
struct sGloveDataTimestamp
{
uint8_t hour = 0;
uint8_t minute = 0;
uint32_t seconds = 0;
uint32_t nanoseconds = 0;
double t = 0;
sGloveDataTimestamp(uint32_t s, uint32_t n) : seconds(s), nanoseconds(n) { t = double(seconds) + double(nanoseconds) * 0.000000001; }
sGloveDataTimestamp(double time) { t = time; }
sGloveDataTimestamp() : t(0.0) {}
bool operator >(const sGloveDataTimestamp& x)
{
return this->t > x.t;
}
bool operator <(const sGloveDataTimestamp& x)
{
return this->t < x.t;
}
bool operator ==(const sGloveDataTimestamp& x)
{
return this->t == x.t;
}
sGloveDataTimestamp operator -(const sGloveDataTimestamp& x)
{
return sGloveDataTimestamp(this->t - x.t);
}
operator const double() {
return t;
}
};
struct sFingerNode {
int node_id;
float quat_x;
float quat_y;
float quat_z;
float quat_w;
};
struct sGloveDeviceData {
uint64_t gloveId = 0;
std::vector<sFingerNode> nodes;
sGloveDataTimestamp timestamp;
};
struct sGloveDeviceBaseInfo
{
uint32_t gloveId = 0; // device serial id
int battery = 0 ;
int signalStrength= 0;
eGloveHandSide handSide = eGloveHandSide::Unknown;
std::string actorName = ""; // Actor 이름 (다중 장비 구분용)
};

View File

@ -1,258 +0,0 @@
//======================================================================================================
// Copyright 2022, NaturalPoint Inc.
//======================================================================================================
#include "dllcommon.h"
#include "GloveDeviceBase.h"
// Optitrack Peripheral Device API
#include "AnalogChannelDescriptor.h"
#include "IDeviceManager.h"
#include "GloveDataFormat.h"
using namespace AnalogSystem;
using namespace OptiTrackPluginDevices;
using namespace GloveDeviceProperties;
OptiTrackPluginDevices::GloveDeviceBase::GloveDeviceBase()
{
this->SetCommonDeviceProperties();
this->SetCommonGloveDeviceProperties();
}
void OptiTrackPluginDevices::GloveDeviceBase::SetCommonDeviceProperties()
{
// Set appropriate default property values (and set advanced state)
ModifyProperty(cPluginDeviceBase::kModelPropName, true, true, false);
ModifyProperty(cPluginDeviceBase::kOrderPropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kDisplayNamePropName, false, false, false);
// Reveal glove related prop name
ModifyProperty(cPluginDeviceBase::kAssetPropName, false, false, false); // name of the paired skeleton asset
// hide default properties that aren't relevant to glove device
ModifyProperty(cPluginDeviceBase::kSyncModePropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kSyncStatusPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kUseExternalClockPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kMocapRateMultiplePropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kScalePropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kCalOffsetPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kCalSquareRotationPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kUserDataPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kZeroPropName, true, true, true);
ModifyProperty(cPluginDeviceBase::kGroupNamePropName, true, true, true);
// hide advanced properties
ModifyProperty(cPluginDeviceBase::kConnectedPropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kNamePropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kChannelCountPropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kAppRunModePropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kMocapSyncFramePropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kSyncFramePropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kNeedDeviceSyncFramePropName, false, false, true);
ModifyProperty(cPluginDeviceBase::kNeedMocapSyncFramePropName, false, false, true);
ModifyProperty(cPluginDeviceBase::kUseDriftCorrectionPropName, false, false, true);
ModifyProperty(cPluginDeviceBase::kMasterSerialPropName, true, false, true);
ModifyProperty(cPluginDeviceBase::kDriftCorrectionPropName, true, false , true);
SetProperty(cPluginDeviceBase::kEnabledPropName, true);
SetProperty(cPluginDeviceBase::kConnectedPropName, true);
SetProperty(cPluginDeviceBase::kMocapRateMultiplePropName, 1);
}
void OptiTrackPluginDevices::GloveDeviceBase::SetCommonGloveDeviceProperties()
{
// Add glove related properties
AddProperty(GloveDeviceProperties::GloveDeviceProp_HandSide, GloveHandSide, kHandSideCount, 0, "Settings", false);
AddProperty(GloveDeviceProperties::GloveDeviceProp_Battery, GloveDeviceProp_BatteryUninitialized, "Settings", false);
AddProperty(GloveDeviceProperties::GloveDeviceProp_SignalStrength, GloveDeviceProp_SignalStrengthUnitialized, "Settings", false);
//AddProperty(GloveDeviceProperties::GloveDeviceProp_Reconnect, false, "Settings", false);
// Modify property visibility
ModifyProperty(GloveDeviceProperties::GloveDeviceProp_SignalStrength, true, false, false, false);
ModifyProperty(GloveDeviceProperties::GloveDeviceProp_HandSide, true, false, false);
ModifyProperty(GloveDeviceProperties::GloveDeviceProp_Battery, true, false, false, false);
}
///////////////////////////////////////////////////////////////////////////////
//
// Setter: Glove Device
//
void OptiTrackPluginDevices::GloveDeviceBase::SetDeviceRate(int rate)
{
mDeviceRateFPS = rate;
mRequestedRateMS = (1.0f / mDeviceRateFPS) * 1000.0f;
return;
}
void OptiTrackPluginDevices::GloveDeviceBase::SetHandSide(eGloveHandSide side)
{
mHandSide = side;
return;
}
void OptiTrackPluginDevices::GloveDeviceBase::SetEnabled(bool enabled)
{
bIsEnabled = enabled;
}
void OptiTrackPluginDevices::GloveDeviceBase::SetCollecting(bool collecting)
{
bIsCollecting = collecting;
}
bool OptiTrackPluginDevices::GloveDeviceBase::SetDeviceSerial(std::string serial)
{
mDeviceSerial = serial;
// Set device serial property
return false;
}
bool OptiTrackPluginDevices::GloveDeviceBase::SetDeviceData(sGloveDeviceData data)
{
mLastGloveData = data;
return true;
}
bool OptiTrackPluginDevices::GloveDeviceBase::SetBatteryLevel(int level)
{
if (SetProperty(GloveDeviceProperties::GloveDeviceProp_Battery, (int)level))
{
mBatteryLevel = level;
return true;
}
return false;
}
bool OptiTrackPluginDevices::GloveDeviceBase::SetSignalStrength(int signal)
{
if (SetProperty(GloveDeviceProperties::GloveDeviceProp_SignalStrength, (int)signal))
{
mSignalStrength = signal;
return true;
}
return false;
}
void OptiTrackPluginDevices::GloveDeviceBase::InitializeGloveProperty()
{
if (mDeviceInfo.handSide == eGloveHandSide::Left)
{
SetProperty(GloveDeviceProperties::GloveDeviceProp_HandSide, 1);
SetProperty(cPluginDeviceBase::kOrderPropName, 1);
bIsInitialized = true;
}
else if (mDeviceInfo.handSide == eGloveHandSide::Right)
{
SetProperty(GloveDeviceProperties::GloveDeviceProp_HandSide, 2);
SetProperty(cPluginDeviceBase::kOrderPropName, 2);
bIsInitialized = true;
}
return;
}
void OptiTrackPluginDevices::GloveDeviceBase::UpdateGloveProperty(const sGloveDeviceBaseInfo& deviceInfo)
{
// update glove property when the device is receiving data.
int deviceState = 0;
GetProperty(kDataStatePropName, deviceState);
if (deviceState == DeviceDataState::DeviceState_ReceivingData)
{
if (mSignalStrength != 1)
{
mSignalStrength = deviceInfo.signalStrength;
double signal = fabs(mSignalStrength);
SetProperty(GloveDeviceProp_SignalStrength, (int)signal);
}
SetProperty(GloveDeviceProp_SignalStrength, -100);
if (mBatteryLevel != deviceInfo.battery)
{
mBatteryLevel = (int)(deviceInfo.battery); //Battery level percentage.
SetProperty(GloveDeviceProp_Battery, (int)mBatteryLevel);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Glove Device Factory
//
void OptiTrackPluginDevices::GloveDeviceFactoryBase::SetCommonGloveDeviceProperties(GloveDeviceBase* pDevice) const
{
// REQUIRED: Set device name/model/serial
pDevice->SetProperty(cPluginDeviceBase::kNamePropName, (char*)DeviceName());
pDevice->SetProperty(cPluginDeviceBase::kDisplayNamePropName, (char*)DeviceName());
pDevice->SetProperty(cPluginDeviceBase::kModelPropName, "Glove Model"); // model
char mDeviceSerial[MAX_PATH];
sprintf_s(mDeviceSerial, "%s-serial", DeviceName());
pDevice->SetProperty(cPluginDeviceBase::kSerialPropName, mDeviceSerial); // device serial (must be unique!)
pDevice->SetProperty(cPluginDeviceBase::kDeviceTypePropName, (long)DeviceType_Glove); // set device type as glove
pDevice->SetProperty(cPluginDeviceBase::kRatePropName, 120.0); // glove sampling rate
pDevice->SetProperty(cPluginDeviceBase::kUseDriftCorrectionPropName, true); // drift correction to fetch most recent data.
pDevice->SetProperty(cPluginDeviceBase::kOrderPropName, (int) eGloveHandSide::Unknown); // device order: (0 = uninitialized, 1=left, 2=right)
}
void OptiTrackPluginDevices::GloveDeviceFactoryBase::SetDeviceIndex(int t_index)
{
mDeviceIndex = t_index;
return;
}
void OptiTrackPluginDevices::GloveDeviceFactoryBase::SetQuaternionDataChannels(GloveDeviceBase* pDevice) const
{
// Set glove data channels:
// 5 fingers * 3 joints per finger * 4 floats per quat (x/y/z/w) = 60 channels
int channelIndex;
int gloveAnalogChannelCount = 60;
char szChannelNames[MAX_PATH];
// add channels
for (int i = 0; i < gloveAnalogChannelCount; i++)
{
int finger = i / 12; // 12 channels per finger
switch (finger)
{
case 0: sprintf_s(szChannelNames, "T"); break;
case 1: sprintf_s(szChannelNames, "I"); break;
case 2: sprintf_s(szChannelNames, "M"); break;
case 3: sprintf_s(szChannelNames, "R"); break;
case 4: sprintf_s(szChannelNames, "P"); break;
}
int joint = (i / 4) % 3; // 3 joints per finger
switch (joint)
{
case 0: sprintf_s(szChannelNames, "%s-MCP", szChannelNames); break;
case 1: sprintf_s(szChannelNames, "%s-PIP", szChannelNames); break;
case 2: sprintf_s(szChannelNames, "%s-DIP", szChannelNames); break;
}
int axis = i % 4; // 4 floats per joint
switch (axis)
{
case 0: sprintf_s(szChannelNames, "%s W", szChannelNames); break;
case 1: sprintf_s(szChannelNames, "%s X", szChannelNames); break;
case 2: sprintf_s(szChannelNames, "%s Y", szChannelNames); break;
case 3: sprintf_s(szChannelNames, "%s Z", szChannelNames); break;
}
channelIndex = pDevice->AddChannelDescriptor(szChannelNames, ChannelType_Float);
}
// enable all channels by default
for (int i = 0; i <= channelIndex; i++)
{
// data channel enabled by default
pDevice->ChannelDescriptor(i)->SetProperty(ChannelProp_Enabled, true);
// hide unused channel properties
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_Units, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_Name, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_MinVoltage, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_MaxVoltage, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_TerminalName, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_TerminalType, true, true);
pDevice->ChannelDescriptor(i)->ModifyProperty(ChannelProp_MaxVoltage, true, true);
}
}

View File

@ -1,180 +0,0 @@
//======================================================================================================
// Copyright 2023, NaturalPoint Inc.
//======================================================================================================
/**
* GloveDeviceBase/GloveDeviceFactory class extends the cPluginDeviceBase and configures data channels and device properties required
* by a glove device in Motive. The purpose of this class is to abstract out setups needed for creating glove device as demonstrated
* in the ExampleGloveDevice. When developing a glove plugin to animate fingers in Motive, the following class can be inherited if needed.
*/
#include <memory>
#include <list>
#include <mutex>
#include <thread>
// OptiTrack Peripheral Device API
#include "PluginDevice.h"
#include "PluginDeviceFactory.h"
#include "GloveDataFormat.h"
namespace OptiTrackPluginDevices
{
class GloveDeviceBase;
class GloveDeviceFactoryBase;
/**
* Common glove device properties used in Motive.
*/
namespace GloveDeviceProperties
{
static const int kHandSideCount = 3;
static const char* GloveHandSide[kHandSideCount] =
{
"Uninitialized",
"Left",
"Right"
};
// Glove type needs to be set at the device level (0 = uninitialized, 1 = left, 2 = right)
static const char* GloveDeviceProp_HandSide = "Hand Side";
static const char* GloveDeviceProp_Battery = "Battery";
static const char* GloveDeviceProp_SignalStrength = "Signal Strength";
static const char* GloveDeviceProp_ServerAddress = "Server Address";
static const char* GloveDeviceProp_Reconnect = "Reconnect";
static const char* GloveDeviceProp_Solver = "Glove Solver";
static const int GloveDeviceProp_BatteryUninitialized = -1;
static const int GloveDeviceProp_SignalStrengthUnitialized = -1;
static const int kGloveAnalogChannelCount = 60;
}
/**
* GloveDeviceFactory class demonstrates how plugin device factory can be set up for creating a glove device in Motive.
* To create a device in Motive, an instance of PLuginDeviceFactory must be created per each device, and then, its ownership must be
* transferred to Motive by using Create method. The GloveDeviceFactory inherits from PLuginDeviceFactory and demonstrates common
* glove properties and data channels can be configured; which is demonstrated in this base class.
*/
class GloveDeviceFactoryBase : public AnalogSystem::PluginDeviceFactory
{
public:
GloveDeviceFactoryBase(std::string deviceName, uint32_t serial) :
AnalogSystem::PluginDeviceFactory(deviceName.c_str()), mDeviceSerial(serial) {}
uint32_t mDeviceSerial = -1;
int mDeviceIndex = 0;
protected:
void SetDeviceIndex(int t_index);
/**
* Sets up quaternion data channels for delivering local rotation of the finger nodes.
* Motive skeleton's hand consists of total 15 finger nodes, 3 per each finger.
* These data channels will get populated by the collection thread running on each device.
* Quaternion values are expected, resulting in total 60 float channels (15 finger nodes * 4 quat floats / node).
* Local rotation data is expected, and both hand data expects right-handed coordinate system with +x axis
* pointing towards the finger tip for left hand and towards the wrist/body for right hand.
*/
void SetQuaternionDataChannels(GloveDeviceBase* pDevice) const;
/**
* Set Common Glove device properties
*/
void SetCommonGloveDeviceProperties(GloveDeviceBase* pDevice) const;
};
/**
* cGloveDeviceBase class is an example class which glove devices could inherit from.
* This class includes basic setups and configurations for glove devices in Motive.
*/
class GloveDeviceBase : public AnalogSystem::cPluginDevice<float>
{
friend class GloveDeviceFactoryBase;
public:
GloveDeviceBase();
~GloveDeviceBase() = default;
void SetCommonDeviceProperties();
void SetCommonGloveDeviceProperties();
protected:
// Device status
bool bIsEnabled = false;
bool bIsCollecting = false;
bool bIsInitialized = false;
bool bIsConfigured = false;
// Device info
sGloveDeviceBaseInfo mGloveInfo;
std::string mDeviceSerial = "";
eGloveHandSide mHandSide = eGloveHandSide::Unknown;
int mBatteryLevel = 0;
int mSignalStrength = 0;
double mDeviceRateFPS = 0;
double mRequestedRateMS = 0.0;
// Glove data
sGloveDeviceData mLastGloveData;
// Collection thread must be created on the device class. Defined in ExampleGloveDevice class.
virtual unsigned long DoCollectionThread() = 0;
/**
* Configure device rate
*/
void SetDeviceRate(int rate);
/**
* Configure hand side
*/
void SetHandSide(eGloveHandSide side);
/**
* Enable or disable device
*/
void SetEnabled(bool enabled);
/**
* Set collection status
*/
void SetCollecting(bool collecting);
/**
* Set device serial string each device must have unique serial
*/
bool SetDeviceSerial(std::string serial);
/**
* Set device data
*/
bool SetDeviceData(sGloveDeviceData data);
/**
* Set device battery level (1-100)
*/
bool SetBatteryLevel(int level);
/**
* Sets the signal stregth (1-128)
*/
bool SetSignalStrength(int signal);
bool IsEnabled() { return bIsEnabled; };
bool IsCollecting() { return bIsCollecting; };
int GetSignalStrength() { return mSignalStrength; }
int GetBatteryLevel() { return mBatteryLevel; }
double GetDeviceRate() { return mDeviceRateFPS; }
sGloveDeviceData GetLastestData() { return mLastGloveData; };
/**
* Initialize the properties for the glove device
*/
void InitializeGloveProperty();
/**
* Updates the device properties. Gets called periodically within collection thread.
* Mainly updates the battery level and signal strength.
*/
void UpdateGloveProperty(const sGloveDeviceBaseInfo& deviceInfo);
sGloveDeviceBaseInfo mDeviceInfo;
};
}

View File

@ -1,185 +0,0 @@
//======================================================================================================
// Copyright 2023, NaturalPoint Inc.
//======================================================================================================
#include "HardwareSimulator.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <windows.h>
using namespace std;
SimulatedPluginDevices::HardwareSimulator::HardwareSimulator()
{}
SimulatedPluginDevices::HardwareSimulator::~HardwareSimulator()
{
bIsRunning = false;
if (mUpdateThread.joinable()) {
mUpdateThread.join();
}
}
void SimulatedPluginDevices::HardwareSimulator::StartData()
{
bIsRunning = true;
mUpdateThread = std::thread(&HardwareSimulator::ReadDataFromCSV, this);
}
void SimulatedPluginDevices::HardwareSimulator::Shutdown()
{
bIsRunning = false;
if (mUpdateThread.joinable())
{
mUpdateThread.join();
}
}
void SimulatedPluginDevices::HardwareSimulator::RegisterDeviceInfoCallback(std::function<void(std::vector<SimulatedDeviceInfo>&)> device_info_callback)
{
mOnDeviceInfoUpdate = device_info_callback;
}
void SimulatedPluginDevices::HardwareSimulator::NotifyDataCallback()
{
if (mOnFrameDataUpdate)
{
mOnFrameDataUpdate(mSimulatedFrameDataSet);
}
}
void SimulatedPluginDevices::HardwareSimulator::NotifyInfoCallback()
{
if (mOnDeviceInfoUpdate)
{
mOnDeviceInfoUpdate(mNewDeviceInfo);
mNewDeviceInfo.clear();
}
}
void SimulatedPluginDevices::HardwareSimulator::AddSimulatedGlove(int deviceId, int nodeCount, int handedness)
{
SimulatedDeviceInfo device(deviceId, nodeCount, handedness);
mSimulatedDeviceInfoSet.push_back(device);
mNewDeviceInfo.push_back(device);
mSimulatedFrameDataSet.push_back(SimulatedGloveFrameData(device.mDeviceSerial, device.mNodeCount));
NotifyInfoCallback();
}
void SimulatedPluginDevices::HardwareSimulator::RegisterFrameDataCallback(std::function<void(std::vector<SimulatedGloveFrameData>&)> data_callback)
{
mOnFrameDataUpdate = data_callback;
}
/**
* [Example] Simply read each frame data from the provided csv file and update the data callback.
*/
bool SimulatedPluginDevices::HardwareSimulator::ReadDataFromCSV()
{
double mRequestedRateMS = (1.0f / mDataSampleRate) * 1000.0f;
std::string filename = GetExePath() + "\\devices\\ExampleGloveData.csv";
// Read the provided example CSV file (60 channels)
std::ifstream fin(filename);
if (!fin.is_open())
{
// Failed to open the device
return false;
}
bool isFirstLine = true;
std::vector<string> field_names;
// loop through lines of data
std::string lineRead;
while (bIsRunning)
{
std::vector<SimulatedFingerData> frame_data;
std::vector<float> jointData;
if (fin.eof())
{
//loop back to begining
fin.clear();
fin.seekg(0, std::ios::beg);
isFirstLine = true;
}
std::getline(fin, lineRead);
std::stringstream lineStream(lineRead);
// Read comma-separated values
std::string val;
std::getline(lineStream, val, ','); // skip first column
while (getline(lineStream, val, ','))
{
if (isFirstLine)
{
field_names.push_back(val);
}
else
{
try
{
float val_f = std::stof(val);
jointData.push_back(val_f);
}
catch (const std::exception* e)
{
// error converting the value. Terminate
return false;
}
if (jointData.size() == 4)
{
SimulatedFingerData finger;
// next finger joint
finger.quat_w = jointData.at(0);
finger.quat_x = jointData.at(1);
finger.quat_y = jointData.at(2);
finger.quat_z = jointData.at(3);
frame_data.push_back(finger);
jointData.clear();
}
}
}
if (isFirstLine)
isFirstLine = false;
else {
if (frame_data.size() != 0)
{
UpdateAllDevicesWithData(frame_data);
}
}
// End of a line sleep
std::this_thread::sleep_for(std::chrono::milliseconds((int)mRequestedRateMS));
}
return true;
}
void SimulatedPluginDevices::HardwareSimulator::UpdateAllDevicesWithData(std::vector<SimulatedFingerData>& data)
{
mDataLock.lock();
// Loop through list of data instances in the frame data vector and update all instances
for (auto& gloveDevice : mSimulatedFrameDataSet)
{
// Set all finger data
gloveDevice.gloveFingerData = data;
}
NotifyDataCallback();
mDataLock.unlock();
}
std::string SimulatedPluginDevices::HardwareSimulator::GetExePath()
{
std::string path;
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\\/");
path = string(buffer).substr(0, pos)/*+"\\system.exe"*/;
return path;
}

View File

@ -1,111 +0,0 @@
////======================================================================================================
//// Copyright 2023, NaturalPoint Inc.
////======================================================================================================
/*
* SimulatedHardware class is used for demonstrating third-party glove SDK DLL to simulate a third-party hardware.
* For the purpose of the example glove device, the finger tracking data is read from the csv file.
*/
#pragma once
#define DATA_SAMPLERATE 120
#include <thread>
#include <mutex>
#include <vector>
#include <functional>
#include <cmath>
#include <unordered_map>
namespace SimulatedPluginDevices {
class HardwareSimulator;
struct SimulatedFingerData
{
float quat_x = 0;
float quat_y = 0;
float quat_z = 0;
float quat_w = 0;
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
SimulatedFingerData() {};
SimulatedFingerData(float x, float y, float z, float w) :
quat_x(x), quat_y(y), quat_z(z), quat_w(w) {}
};
struct SimulatedGloveFrameData {
int mDeviceSerial = 0;
int mChannelCount = 0;
int kChannelPerNode = 4;
int mNodeCount = 0;
std::vector<SimulatedFingerData> gloveFingerData; // for glove data
SimulatedGloveFrameData() {}
SimulatedGloveFrameData(int deviceSerial, int nodeCount) :
mDeviceSerial(deviceSerial),
mNodeCount(nodeCount)
{
mChannelCount = mNodeCount * kChannelPerNode;
gloveFingerData.resize(mNodeCount);
}
};
struct SimulatedDeviceInfo {
int mDeviceSerial = 0; // device serial id
int mBattery = 100;
int mSignalStrength = 100;
int mHandSide = 0;
int mNodeCount = 0;
int mChannelCount = 0;
int kChannelPerNode = 4;
SimulatedDeviceInfo() {}
SimulatedDeviceInfo(int deviceSerial, int channelCount):
mDeviceSerial(deviceSerial), mChannelCount(channelCount)
{}
SimulatedDeviceInfo(int deviceSerial, int nodeCount, int handSide) :
mDeviceSerial(deviceSerial), mHandSide(handSide), mNodeCount(nodeCount)
{
mChannelCount = nodeCount * kChannelPerNode;
}
};
/// <summary>
/// Simple simulator for outputting sine wave channel data.
/// </summary>
class HardwareSimulator {
public:
HardwareSimulator();
~HardwareSimulator();
void AddSimulatedGlove(int deviceId, int nodeCount, int handedness);
void RegisterFrameDataCallback(std::function<void(std::vector<SimulatedGloveFrameData>&)> data_callback);
void RegisterDeviceInfoCallback(std::function<void(std::vector<SimulatedDeviceInfo>&)> device_info_callback);
void StartData();
void Shutdown();
private:
bool bIsRunning = false;
std::thread mUpdateThread;
void NotifyDataCallback();
void NotifyInfoCallback();
bool ReadDataFromCSV();
static std::string GetExePath();
void UpdateAllDevicesWithData(std::vector<SimulatedFingerData>& data);
std::vector<SimulatedGloveFrameData> mSimulatedFrameDataSet;
std::vector<SimulatedDeviceInfo> mSimulatedDeviceInfoSet;
std::vector<SimulatedDeviceInfo> mNewDeviceInfo;
std::function<void(std::vector<SimulatedGloveFrameData>&)> mOnFrameDataUpdate;
std::function<void(std::vector<SimulatedDeviceInfo>&)> mOnDeviceInfoUpdate;
const double mDataSampleRate = DATA_SAMPLERATE;
protected:
std::recursive_mutex mDataLock;
};
}

View File

@ -1,161 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
#include "LZ4Wrapper.h"
#include <cstring>
#include <stdexcept>
#include <windows.h>
// Unity LZ4 DLL 동적 로딩
static HMODULE lz4Module = nullptr;
static decltype(&Unity_LZ4_uncompressSize) pUnity_LZ4_uncompressSize = nullptr;
static decltype(&Unity_LZ4_decompress) pUnity_LZ4_decompress = nullptr;
static bool LoadUnityLZ4()
{
if (lz4Module == nullptr) {
// 다양한 경로에서 Unity LZ4 DLL 로드 시도
const wchar_t* dllPaths[] = {
L"lz4.dll", // 현재 디렉토리
L".\\lz4.dll", // 명시적 현재 디렉토리
L"x64\\Debug\\lz4.dll", // 디버그 폴더
L"C:\\Users\\user\\Documents\\Streamingle_URP\\Assets\\External\\Rokoko\\Scripts\\Plugins\\LZ4\\x86_64\\lz4.dll" // Unity 절대 경로
};
for (const auto& path : dllPaths) {
lz4Module = LoadLibrary(path);
if (lz4Module != nullptr) {
// DLL 로드 성공 - 함수 포인터 획득
pUnity_LZ4_uncompressSize = (decltype(pUnity_LZ4_uncompressSize))GetProcAddress(lz4Module, "Unity_LZ4_uncompressSize");
pUnity_LZ4_decompress = (decltype(pUnity_LZ4_decompress))GetProcAddress(lz4Module, "Unity_LZ4_decompress");
if (pUnity_LZ4_uncompressSize != nullptr && pUnity_LZ4_decompress != nullptr) {
// 성공
break;
} else {
// 함수를 찾지 못함 - DLL 언로드하고 다음 시도
FreeLibrary(lz4Module);
lz4Module = nullptr;
pUnity_LZ4_uncompressSize = nullptr;
pUnity_LZ4_decompress = nullptr;
}
}
}
}
return (lz4Module != nullptr && pUnity_LZ4_uncompressSize != nullptr && pUnity_LZ4_decompress != nullptr);
}
namespace RokokoIntegration
{
std::vector<uint8_t> LZ4Wrapper::Decompress(const uint8_t* compressedData, int compressedSize)
{
try {
// 입력 데이터 검증
if (!compressedData || compressedSize <= 0) {
return {};
}
// Unity LZ4 DLL 로드
if (!LoadUnityLZ4()) {
return {};
}
// Unity 방식 정확히 구현
// 1. Unity_LZ4_uncompressSize로 압축 해제된 크기 구하기
int uncompressedSize = pUnity_LZ4_uncompressSize(
reinterpret_cast<const char*>(compressedData),
compressedSize
);
if (uncompressedSize <= 0) {
return {};
}
// 크기 유효성 검사
if (uncompressedSize > MAX_DECOMPRESSED_SIZE) {
return {};
}
// 2. Unity_LZ4_decompress로 압축 해제
std::vector<uint8_t> decompressed(uncompressedSize);
int result = pUnity_LZ4_decompress(
reinterpret_cast<const char*>(compressedData),
compressedSize,
reinterpret_cast<char*>(decompressed.data()),
uncompressedSize
);
// Unity에서는 result != 0이면 실패
if (result != 0) {
return {};
}
return decompressed;
} catch (...) {
// 모든 예외 상황에서 안전하게 빈 벡터 반환
return {};
}
}
bool LZ4Wrapper::IsValidLZ4Data(const uint8_t* data, int size)
{
if (!data || size < 4) {
return false;
}
// Rokoko Studio의 LZ4 데이터는 일반적으로 JSON이 아니므로
// 첫 번째 바이트가 '{'가 아닌 경우 LZ4로 간주
if (size > 0 && data[0] == '{') {
return false; // JSON 데이터는 LZ4가 아님
}
// 기본적인 LZ4 매직 넘버 확인
// LZ4 프레임 헤더의 일부 패턴 확인
if (size >= 4) {
// LZ4 프레임 헤더의 매직 넘버 (0x184D2204)
if (data[0] == 0x04 && data[1] == 0x22 && data[2] == 0x4D && data[3] == 0x18) {
return true;
}
}
// 매직 넘버가 없어도 압축된 데이터로 간주 (Rokoko Studio 특성상)
return true;
}
int LZ4Wrapper::GetDecompressedSize(const uint8_t* compressedData, int compressedSize)
{
try {
// Unity LZ4 DLL 로드
if (!LoadUnityLZ4()) {
return -1;
}
// Unity 방식으로 압축 해제된 크기 구하기
int decompressedSize = pUnity_LZ4_uncompressSize(
reinterpret_cast<const char*>(compressedData),
compressedSize
);
return decompressedSize;
} catch (...) {
return -1;
}
}
bool LZ4Wrapper::ValidateDecompressedSize(int compressedSize, int decompressedSize)
{
// 압축 해제된 크기가 합리적인 범위인지 확인
if (decompressedSize <= 0 || decompressedSize > MAX_DECOMPRESSED_SIZE) {
return false;
}
// 압축률이 합리적인지 확인 (일반적으로 1:1 ~ 1:10)
if (decompressedSize < compressedSize || decompressedSize > compressedSize * 10) {
return false;
}
return true;
}
}

View File

@ -1,62 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* LZ4Wrapper class provides LZ4 decompression functionality for Rokoko glove data.
* This wrapper handles safe decompression and validation of compressed data.
*/
#pragma once
#include <vector>
#include <cstdint>
// Unity LZ4 함수들 선언
extern "C" {
int Unity_LZ4_uncompressSize(const char* srcBuffer, int srcSize);
int Unity_LZ4_decompress(const char* src, int srcSize, char* dst, int dstCapacity);
}
namespace RokokoIntegration
{
class LZ4Wrapper
{
public:
/**
* Decompresses LZ4 compressed data
* @param compressedData Pointer to compressed data
* @param compressedSize Size of compressed data
* @return Decompressed data as vector, empty if decompression fails
*/
static std::vector<uint8_t> Decompress(const uint8_t* compressedData, int compressedSize);
/**
* Validates if the data appears to be valid LZ4 compressed data
* @param data Pointer to data to validate
* @param size Size of data
* @return true if data appears to be valid LZ4 data
*/
static bool IsValidLZ4Data(const uint8_t* data, int size);
/**
* Gets the decompressed size from LZ4 header
* @param compressedData Pointer to compressed data
* @param compressedSize Size of compressed data
* @return Decompressed size, -1 if invalid
*/
static int GetDecompressedSize(const uint8_t* compressedData, int compressedSize);
private:
/**
* Validates decompressed size is reasonable
* @param compressedSize Size of compressed data
* @param decompressedSize Size of decompressed data
* @return true if sizes are reasonable
*/
static bool ValidateDecompressedSize(int compressedSize, int decompressedSize);
/**
* Maximum reasonable decompressed size (10MB)
*/
static const int MAX_DECOMPRESSED_SIZE = 10 * 1024 * 1024;
};
}

View File

@ -1,148 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* RokokoData.h defines the data structures for Rokoko Studio LiveFrame_v4 format.
* These structures match the JSON format used by Rokoko Unity scripts.
*/
#pragma once
#include <vector>
#include <memory>
#include <optional>
#include <string>
namespace RokokoData
{
// Vector3 structure for position data
struct Vector3Frame
{
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
};
// Vector4 structure for quaternion rotation data
struct Vector4Frame
{
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float w = 1.0f;
};
// Actor joint frame containing position and rotation
struct ActorJointFrame
{
Vector3Frame position;
Vector4Frame rotation;
};
// Body structure containing full skeleton (Unity BodyFrame와 동일)
// ✅ OPTIMIZATION: Using std::optional instead of shared_ptr for stack allocation (zero heap allocations)
struct Body
{
// 전신 스켈레톤 데이터 (Unity BodyFrame과 동일)
std::optional<ActorJointFrame> hip;
std::optional<ActorJointFrame> spine;
std::optional<ActorJointFrame> chest;
std::optional<ActorJointFrame> neck;
std::optional<ActorJointFrame> head;
std::optional<ActorJointFrame> leftShoulder;
std::optional<ActorJointFrame> leftUpperArm;
std::optional<ActorJointFrame> leftLowerArm;
std::optional<ActorJointFrame> leftHand;
std::optional<ActorJointFrame> rightShoulder;
std::optional<ActorJointFrame> rightUpperArm;
std::optional<ActorJointFrame> rightLowerArm;
std::optional<ActorJointFrame> rightHand;
// 다리 데이터 (필요시)
std::optional<ActorJointFrame> leftUpLeg;
std::optional<ActorJointFrame> leftLeg;
std::optional<ActorJointFrame> leftFoot;
std::optional<ActorJointFrame> leftToe;
std::optional<ActorJointFrame> leftToeEnd;
std::optional<ActorJointFrame> rightUpLeg;
std::optional<ActorJointFrame> rightLeg;
std::optional<ActorJointFrame> rightFoot;
std::optional<ActorJointFrame> rightToe;
std::optional<ActorJointFrame> rightToeEnd;
// Left hand finger joints
std::optional<ActorJointFrame> leftThumbProximal;
std::optional<ActorJointFrame> leftThumbMedial;
std::optional<ActorJointFrame> leftThumbDistal;
std::optional<ActorJointFrame> leftThumbTip;
std::optional<ActorJointFrame> leftIndexProximal;
std::optional<ActorJointFrame> leftIndexMedial;
std::optional<ActorJointFrame> leftIndexDistal;
std::optional<ActorJointFrame> leftIndexTip;
std::optional<ActorJointFrame> leftMiddleProximal;
std::optional<ActorJointFrame> leftMiddleMedial;
std::optional<ActorJointFrame> leftMiddleDistal;
std::optional<ActorJointFrame> leftMiddleTip;
std::optional<ActorJointFrame> leftRingProximal;
std::optional<ActorJointFrame> leftRingMedial;
std::optional<ActorJointFrame> leftRingDistal;
std::optional<ActorJointFrame> leftRingTip;
std::optional<ActorJointFrame> leftLittleProximal;
std::optional<ActorJointFrame> leftLittleMedial;
std::optional<ActorJointFrame> leftLittleDistal;
std::optional<ActorJointFrame> leftLittleTip;
// Right hand finger joints (similar structure)
std::optional<ActorJointFrame> rightThumbProximal;
std::optional<ActorJointFrame> rightThumbMedial;
std::optional<ActorJointFrame> rightThumbDistal;
std::optional<ActorJointFrame> rightThumbTip;
std::optional<ActorJointFrame> rightIndexProximal;
std::optional<ActorJointFrame> rightIndexMedial;
std::optional<ActorJointFrame> rightIndexDistal;
std::optional<ActorJointFrame> rightIndexTip;
std::optional<ActorJointFrame> rightMiddleProximal;
std::optional<ActorJointFrame> rightMiddleMedial;
std::optional<ActorJointFrame> rightMiddleDistal;
std::optional<ActorJointFrame> rightMiddleTip;
std::optional<ActorJointFrame> rightRingProximal;
std::optional<ActorJointFrame> rightRingMedial;
std::optional<ActorJointFrame> rightRingDistal;
std::optional<ActorJointFrame> rightRingTip;
std::optional<ActorJointFrame> rightLittleProximal;
std::optional<ActorJointFrame> rightLittleMedial;
std::optional<ActorJointFrame> rightLittleDistal;
std::optional<ActorJointFrame> rightLittleTip;
};
// Actor data structure
struct ActorData
{
std::string id;
std::string name;
Body body;
};
// Scene structure containing actors
struct SceneFrame
{
std::vector<ActorData> actors;
};
// Main LiveFrame_v4 structure
struct LiveFrame_v4
{
double timestamp = 0.0;
SceneFrame scene;
};
}

View File

@ -1,214 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
#include "RokokoDataConverter.h"
#include "RokokoData.h"
#include <cmath>
#include <sstream>
#include <algorithm>
namespace RokokoIntegration
{
// 정적 상수는 헤더에서 inline으로 정의됨
sGloveDeviceData RokokoDataConverter::ConvertRokokoToOptiTrack(const RokokoData::LiveFrame_v4& rokokoFrame)
{
sGloveDeviceData optiTrackData;
try {
// 기본 데이터 설정
optiTrackData.gloveId = 1; // 기본 장갑 ID
optiTrackData.timestamp = 0.0; // 타임스탬프는 나중에 설정
// 15개 OptiTrack 관절 노드 초기화
optiTrackData.nodes.resize(TOTAL_OPTITRACK_JOINTS);
// 검증: actors가 존재하는지 확인
if (rokokoFrame.scene.actors.empty()) {
optiTrackData.nodes.clear();
return optiTrackData;
}
const auto& actor = rokokoFrame.scene.actors[0];
// ✅ OPTIMIZATION: Use has_value() for optional instead of implicit bool conversion
// 손가락별 데이터 매핑 (왼손)
// 엄지손가락 (Thumb)
if (actor.body.leftThumbMedial.has_value()) ConvertJoint(*actor.body.leftThumbMedial, optiTrackData.nodes[0]); // MP
if (actor.body.leftThumbDistal.has_value()) ConvertJoint(*actor.body.leftThumbDistal, optiTrackData.nodes[1]); // PIP
if (actor.body.leftThumbTip.has_value()) ConvertJoint(*actor.body.leftThumbTip, optiTrackData.nodes[2]); // DIP
// 검지손가락 (Index)
if (actor.body.leftIndexMedial.has_value()) ConvertJoint(*actor.body.leftIndexMedial, optiTrackData.nodes[3]); // MP
if (actor.body.leftIndexDistal.has_value()) ConvertJoint(*actor.body.leftIndexDistal, optiTrackData.nodes[4]); // PIP
if (actor.body.leftIndexTip.has_value()) ConvertJoint(*actor.body.leftIndexTip, optiTrackData.nodes[5]); // DIP
// 중지손가락 (Middle)
if (actor.body.leftMiddleMedial.has_value()) ConvertJoint(*actor.body.leftMiddleMedial, optiTrackData.nodes[6]); // MP
if (actor.body.leftMiddleDistal.has_value()) ConvertJoint(*actor.body.leftMiddleDistal, optiTrackData.nodes[7]); // PIP
if (actor.body.leftMiddleTip.has_value()) ConvertJoint(*actor.body.leftMiddleTip, optiTrackData.nodes[8]); // DIP
// 약지손가락 (Ring)
if (actor.body.leftRingMedial.has_value()) ConvertJoint(*actor.body.leftRingMedial, optiTrackData.nodes[9]); // MP
if (actor.body.leftRingDistal.has_value()) ConvertJoint(*actor.body.leftRingDistal, optiTrackData.nodes[10]); // PIP
if (actor.body.leftRingTip.has_value()) ConvertJoint(*actor.body.leftRingTip, optiTrackData.nodes[11]); // DIP
// 새끼손가락 (Little)
if (actor.body.leftLittleMedial.has_value()) ConvertJoint(*actor.body.leftLittleMedial, optiTrackData.nodes[12]); // MP
if (actor.body.leftLittleDistal.has_value()) ConvertJoint(*actor.body.leftLittleDistal, optiTrackData.nodes[13]); // PIP
if (actor.body.leftLittleTip.has_value()) ConvertJoint(*actor.body.leftLittleTip, optiTrackData.nodes[14]); // DIP
// 노드 ID 설정
for (int i = 0; i < TOTAL_OPTITRACK_JOINTS; i++) {
optiTrackData.nodes[i].node_id = i;
}
} catch (...) {
// 에러 발생 시 빈 데이터 반환
optiTrackData.nodes.clear();
}
return optiTrackData;
}
bool RokokoDataConverter::ConvertJoint(const RokokoData::ActorJointFrame& rokokoJoint, sFingerNode& optiTrackNode)
{
try {
// 쿼터니언 변환
ConvertQuaternion(rokokoJoint.rotation,
optiTrackNode.quat_w,
optiTrackNode.quat_x,
optiTrackNode.quat_y,
optiTrackNode.quat_z);
// 쿼터니언 정규화
NormalizeQuaternion(optiTrackNode.quat_w,
optiTrackNode.quat_x,
optiTrackNode.quat_y,
optiTrackNode.quat_z);
// 쿼터니언 유효성 검사
if (!ValidateQuaternion(optiTrackNode.quat_w,
optiTrackNode.quat_x,
optiTrackNode.quat_y,
optiTrackNode.quat_z)) {
return false;
}
return true;
} catch (...) {
return false;
}
}
bool RokokoDataConverter::ValidateOptiTrackData(const sGloveDeviceData& gloveData)
{
// 기본 검증
if (gloveData.nodes.size() != TOTAL_OPTITRACK_JOINTS) {
return false;
}
// 각 노드 검증
for (const auto& node : gloveData.nodes) {
if (!ValidateQuaternion(node.quat_w, node.quat_x, node.quat_y, node.quat_z)) {
return false;
}
}
return true;
}
std::string RokokoDataConverter::GetMappingInfo()
{
std::ostringstream oss;
oss << "Rokoko to OptiTrack Finger Joint Mapping:\n";
oss << "Total Rokoko joints: " << TOTAL_ROKOKO_JOINTS << " (4 per finger)\n";
oss << "Total OptiTrack joints: " << TOTAL_OPTITRACK_JOINTS << " (3 per finger)\n";
oss << "Mapping removes proximal joints and keeps:\n";
oss << " - Medial (MP): Metacarpophalangeal\n";
oss << " - Distal (PIP): Proximal Interphalangeal\n";
oss << " - Tip (DIP): Distal Interphalangeal\n";
return oss.str();
}
void RokokoDataConverter::MapFingerJoints(const std::vector<RokokoData::ActorJointFrame>& rokokoFingers,
std::vector<sFingerNode>& optiTrackNodes)
{
if (rokokoFingers.size() != TOTAL_ROKOKO_JOINTS || optiTrackNodes.size() != TOTAL_OPTITRACK_JOINTS) {
return;
}
// 매핑 테이블을 사용하여 관절 변환
for (int i = 0; i < TOTAL_OPTITRACK_JOINTS; i++) {
int rokokoIndex = JOINT_MAPPING[i];
if (rokokoIndex >= 0 && rokokoIndex < TOTAL_ROKOKO_JOINTS) {
ConvertJoint(rokokoFingers[rokokoIndex], optiTrackNodes[i]);
}
}
}
void RokokoDataConverter::ConvertQuaternion(const RokokoData::Vector4Frame& rokokoQuat,
float& quat_w, float& quat_x, float& quat_y, float& quat_z)
{
// Rokoko 쿼터니언을 OptiTrack 형식으로 복사
quat_w = rokokoQuat.w;
quat_x = rokokoQuat.x;
quat_y = rokokoQuat.y;
quat_z = rokokoQuat.z;
}
void RokokoDataConverter::NormalizeQuaternion(float& w, float& x, float& y, float& z)
{
float length = std::sqrt(w * w + x * x + y * y + z * z);
if (length > 0.0f) {
float invLength = 1.0f / length;
w *= invLength;
x *= invLength;
y *= invLength;
z *= invLength;
} else {
// 유효하지 않은 쿼터니언인 경우 기본값 설정
w = 1.0f;
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
}
bool RokokoDataConverter::ValidateQuaternion(float w, float x, float y, float z)
{
// NaN 체크
if (std::isnan(w) || std::isnan(x) || std::isnan(y) || std::isnan(z)) {
return false;
}
// 무한대 체크
if (std::isinf(w) || std::isinf(x) || std::isinf(y) || std::isinf(z)) {
return false;
}
// 쿼터니언 길이 체크 (정규화된 경우 1.0에 가까워야 함)
float length = std::sqrt(w * w + x * x + y * y + z * z);
if (std::abs(length - 1.0f) > 0.1f) {
return false;
}
return true;
}
void RokokoDataConverter::ApplyHandCoordinateSystem(bool isLeftHand, float& x, float& y, float& z)
{
// 좌우손 좌표계 변환
if (isLeftHand) {
// 왼손: +X축이 손가락 끝 방향
// 변환 없음 (기본값)
} else {
// 오른손: +X축이 손목/몸 방향
x = -x; // X축 반전
}
}
}

View File

@ -1,116 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* RokokoDataConverter class provides data conversion functionality from Rokoko format to OptiTrack format.
* This converter handles the mapping of 20 Rokoko finger joints to 15 OptiTrack finger joints.
*/
#pragma once
#include <vector>
#include <memory>
#include "GloveDataFormat.h"
// Forward declarations
namespace RokokoData
{
struct Vector3Frame;
struct Vector4Frame;
struct ActorJointFrame;
struct ActorData;
struct LiveFrame_v4;
}
namespace RokokoIntegration
{
class RokokoDataConverter
{
public:
/**
* Converts Rokoko LiveFrame_v4 data to OptiTrack glove data format
* @param rokokoFrame Input Rokoko frame data
* @return Converted OptiTrack glove data
*/
static sGloveDeviceData ConvertRokokoToOptiTrack(const RokokoData::LiveFrame_v4& rokokoFrame);
/**
* Converts Rokoko finger joint data to OptiTrack finger node format
* @param rokokoJoint Input Rokoko joint data
* @param optiTrackNode Output OptiTrack node data
* @return true if conversion successful
*/
static bool ConvertJoint(const RokokoData::ActorJointFrame& rokokoJoint, sFingerNode& optiTrackNode);
/**
* Validates converted OptiTrack data
* @param gloveData Data to validate
* @return true if data is valid
*/
static bool ValidateOptiTrackData(const sGloveDeviceData& gloveData);
/**
* Gets the mapping information for debugging
* @return String containing mapping details
*/
static std::string GetMappingInfo();
private:
/**
* Maps Rokoko finger joints to OptiTrack format
* Maps 20 Rokoko joints (4 per finger) to 15 OptiTrack joints (3 per finger)
* Removes proximal joints and keeps medial, distal, tip
*/
static void MapFingerJoints(const std::vector<RokokoData::ActorJointFrame>& rokokoFingers,
std::vector<sFingerNode>& optiTrackNodes);
/**
* Converts quaternion from Rokoko format to OptiTrack format
* @param rokokoQuat Input Rokoko quaternion
* @param optiTrackQuat Output OptiTrack quaternion
*/
static void ConvertQuaternion(const RokokoData::Vector4Frame& rokokoQuat,
float& quat_w, float& quat_x, float& quat_y, float& quat_z);
/**
* Normalizes quaternion values
* @param w, x, y, z Quaternion components (modified in place)
*/
static void NormalizeQuaternion(float& w, float& x, float& y, float& z);
/**
* Validates quaternion values
* @param w, x, y, z Quaternion components
* @return true if quaternion is valid
*/
static bool ValidateQuaternion(float w, float x, float y, float z);
/**
* Applies coordinate system conversion for left/right hands
* @param isLeftHand true if left hand, false if right hand
* @param x, y, z Position coordinates (modified in place)
*/
static void ApplyHandCoordinateSystem(bool isLeftHand, float& x, float& y, float& z);
// Finger mapping constants
static inline const int ROKOKO_JOINTS_PER_FINGER = 4; // Proximal, Medial, Distal, Tip
static inline const int OPTITRACK_JOINTS_PER_FINGER = 3; // MP, PIP, DIP
static inline const int TOTAL_FINGERS = 5; // Thumb, Index, Middle, Ring, Little
static inline const int TOTAL_ROKOKO_JOINTS = TOTAL_FINGERS * ROKOKO_JOINTS_PER_FINGER; // 20
static inline const int TOTAL_OPTITRACK_JOINTS = TOTAL_FINGERS * OPTITRACK_JOINTS_PER_FINGER; // 15
// Joint mapping table: Rokoko index -> OptiTrack index
// Removes proximal joints (index 0, 4, 8, 12, 16)
static inline const int JOINT_MAPPING[15] = {
// Thumb: Medial(1), Distal(2), Tip(3) -> MP(0), PIP(1), DIP(2)
1, 2, 3,
// Index: Medial(5), Distal(6), Tip(7) -> MP(3), PIP(4), DIP(5)
5, 6, 7,
// Middle: Medial(9), Distal(10), Tip(11) -> MP(6), PIP(7), DIP(8)
9, 10, 11,
// Ring: Medial(13), Distal(14), Tip(15) -> MP(9), PIP(10), DIP(11)
13, 14, 15,
// Little: Medial(17), Distal(18), Tip(19) -> MP(12), PIP(13), DIP(14)
17, 18, 19
};
};
}

View File

@ -1,339 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
#include "RokokoDataParser.h"
#include "RokokoData.h"
#include <sstream>
#include <iostream>
#include <cstring>
#include <cmath>
namespace RokokoIntegration
{
bool RokokoDataParser::ParseLiveFrame(const std::string& jsonString, RokokoData::LiveFrame_v4& frame)
{
try {
// nlohmann/json을 사용하여 JSON 파싱
nlohmann::json j = nlohmann::json::parse(jsonString);
// Unity JsonLiveSerializerV3.cs와 동일한 구조로 파싱
// Scene 데이터 파싱
if (j.contains("scene")) {
auto& scene = j["scene"];
// 타임스탬프
if (scene.contains("timestamp")) {
frame.timestamp = scene["timestamp"];
}
// Actors 파싱
if (scene.contains("actors") && scene["actors"].is_array()) {
auto& actors = scene["actors"];
for (const auto& actorJson : actors) {
RokokoData::ActorData actor;
// Actor 기본 정보
if (actorJson.contains("name")) {
actor.name = actorJson["name"];
}
// Body 데이터 파싱
if (actorJson.contains("body")) {
ParseBodyFrame(actorJson["body"], actor.body);
}
frame.scene.actors.push_back(actor);
}
}
}
return true;
} catch (const nlohmann::json::exception& e) {
// JSON 파싱 에러 처리
std::cerr << "JSON parsing error: " << e.what() << std::endl;
return false;
} catch (...) {
// 기타 예외 처리
std::cerr << "Unknown error during JSON parsing" << std::endl;
return false;
}
}
void RokokoDataParser::ParseBodyFrame(const nlohmann::json& bodyJson, RokokoData::Body& body)
{
// Unity JsonLiveSerializerV3.cs의 BodyFrame 구조와 동일하게 파싱
// === 전신 스켈레톤 데이터 파싱 (Unity BodyFrame과 동일) ===
// 몸통 파싱
ParseFingerJoint(bodyJson, "hip", body.hip);
ParseFingerJoint(bodyJson, "spine", body.spine);
ParseFingerJoint(bodyJson, "chest", body.chest);
ParseFingerJoint(bodyJson, "neck", body.neck);
ParseFingerJoint(bodyJson, "head", body.head);
// 왼쪽 팔 파싱
ParseFingerJoint(bodyJson, "leftShoulder", body.leftShoulder);
ParseFingerJoint(bodyJson, "leftUpperArm", body.leftUpperArm);
ParseFingerJoint(bodyJson, "leftLowerArm", body.leftLowerArm);
ParseFingerJoint(bodyJson, "leftHand", body.leftHand);
// 오른쪽 팔 파싱
ParseFingerJoint(bodyJson, "rightShoulder", body.rightShoulder);
ParseFingerJoint(bodyJson, "rightUpperArm", body.rightUpperArm);
ParseFingerJoint(bodyJson, "rightLowerArm", body.rightLowerArm);
ParseFingerJoint(bodyJson, "rightHand", body.rightHand);
// 다리 파싱 (필요시)
ParseFingerJoint(bodyJson, "leftUpLeg", body.leftUpLeg);
ParseFingerJoint(bodyJson, "leftLeg", body.leftLeg);
ParseFingerJoint(bodyJson, "leftFoot", body.leftFoot);
ParseFingerJoint(bodyJson, "leftToe", body.leftToe);
ParseFingerJoint(bodyJson, "leftToeEnd", body.leftToeEnd);
ParseFingerJoint(bodyJson, "rightUpLeg", body.rightUpLeg);
ParseFingerJoint(bodyJson, "rightLeg", body.rightLeg);
ParseFingerJoint(bodyJson, "rightFoot", body.rightFoot);
ParseFingerJoint(bodyJson, "rightToe", body.rightToe);
ParseFingerJoint(bodyJson, "rightToeEnd", body.rightToeEnd);
// === 손가락 데이터 파싱 ===
// 왼손 손가락 데이터 파싱
ParseFingerJoint(bodyJson, "leftThumbProximal", body.leftThumbProximal);
ParseFingerJoint(bodyJson, "leftThumbMedial", body.leftThumbMedial);
ParseFingerJoint(bodyJson, "leftThumbDistal", body.leftThumbDistal);
ParseFingerJoint(bodyJson, "leftThumbTip", body.leftThumbTip);
ParseFingerJoint(bodyJson, "leftIndexProximal", body.leftIndexProximal);
ParseFingerJoint(bodyJson, "leftIndexMedial", body.leftIndexMedial);
ParseFingerJoint(bodyJson, "leftIndexDistal", body.leftIndexDistal);
ParseFingerJoint(bodyJson, "leftIndexTip", body.leftIndexTip);
ParseFingerJoint(bodyJson, "leftMiddleProximal", body.leftMiddleProximal);
ParseFingerJoint(bodyJson, "leftMiddleMedial", body.leftMiddleMedial);
ParseFingerJoint(bodyJson, "leftMiddleDistal", body.leftMiddleDistal);
ParseFingerJoint(bodyJson, "leftMiddleTip", body.leftMiddleTip);
ParseFingerJoint(bodyJson, "leftRingProximal", body.leftRingProximal);
ParseFingerJoint(bodyJson, "leftRingMedial", body.leftRingMedial);
ParseFingerJoint(bodyJson, "leftRingDistal", body.leftRingDistal);
ParseFingerJoint(bodyJson, "leftRingTip", body.leftRingTip);
ParseFingerJoint(bodyJson, "leftLittleProximal", body.leftLittleProximal);
ParseFingerJoint(bodyJson, "leftLittleMedial", body.leftLittleMedial);
ParseFingerJoint(bodyJson, "leftLittleDistal", body.leftLittleDistal);
ParseFingerJoint(bodyJson, "leftLittleTip", body.leftLittleTip);
// 오른손 손가락 데이터 파싱
ParseFingerJoint(bodyJson, "rightThumbProximal", body.rightThumbProximal);
ParseFingerJoint(bodyJson, "rightThumbMedial", body.rightThumbMedial);
ParseFingerJoint(bodyJson, "rightThumbDistal", body.rightThumbDistal);
ParseFingerJoint(bodyJson, "rightThumbTip", body.rightThumbTip);
ParseFingerJoint(bodyJson, "rightIndexProximal", body.rightIndexProximal);
ParseFingerJoint(bodyJson, "rightIndexMedial", body.rightIndexMedial);
ParseFingerJoint(bodyJson, "rightIndexDistal", body.rightIndexDistal);
ParseFingerJoint(bodyJson, "rightIndexTip", body.rightIndexTip);
ParseFingerJoint(bodyJson, "rightMiddleProximal", body.rightMiddleProximal);
ParseFingerJoint(bodyJson, "rightMiddleMedial", body.rightMiddleMedial);
ParseFingerJoint(bodyJson, "rightMiddleDistal", body.rightMiddleDistal);
ParseFingerJoint(bodyJson, "rightMiddleTip", body.rightMiddleTip);
ParseFingerJoint(bodyJson, "rightRingProximal", body.rightRingProximal);
ParseFingerJoint(bodyJson, "rightRingMedial", body.rightRingMedial);
ParseFingerJoint(bodyJson, "rightRingDistal", body.rightRingDistal);
ParseFingerJoint(bodyJson, "rightRingTip", body.rightRingTip);
ParseFingerJoint(bodyJson, "rightLittleProximal", body.rightLittleProximal);
ParseFingerJoint(bodyJson, "rightLittleMedial", body.rightLittleMedial);
ParseFingerJoint(bodyJson, "rightLittleDistal", body.rightLittleDistal);
ParseFingerJoint(bodyJson, "rightLittleTip", body.rightLittleTip);
}
void RokokoDataParser::ParseFingerJoint(const nlohmann::json& bodyJson, const std::string& jointName, std::optional<RokokoData::ActorJointFrame>& joint)
{
if (bodyJson.contains(jointName)) {
auto& jointJson = bodyJson[jointName];
// ✅ OPTIMIZATION: Direct assignment to optional (stack allocation, no heap)
RokokoData::ActorJointFrame tempJoint;
// Position 파싱
if (jointJson.contains("position")) {
auto& pos = jointJson["position"];
tempJoint.position.x = pos.value("x", 0.0f);
tempJoint.position.y = pos.value("y", 0.0f);
tempJoint.position.z = pos.value("z", 0.0f);
}
// Rotation 파싱
if (jointJson.contains("rotation")) {
auto& rot = jointJson["rotation"];
tempJoint.rotation.x = rot.value("x", 0.0f);
tempJoint.rotation.y = rot.value("y", 0.0f);
tempJoint.rotation.z = rot.value("z", 0.0f);
tempJoint.rotation.w = rot.value("w", 1.0f);
// 쿼터니언 정규화
NormalizeQuaternion(tempJoint.rotation.x, tempJoint.rotation.y, tempJoint.rotation.z, tempJoint.rotation.w);
}
// Assign to optional
joint = tempJoint;
}
}
bool RokokoDataParser::ValidateFrameData(const RokokoData::LiveFrame_v4& frame)
{
try {
// 기본 검증
if (frame.scene.actors.empty()) {
return false;
}
const auto& actor = frame.scene.actors[0];
// 손가락 데이터 검증 (왼손 엄지손가락만 체크)
// ✅ OPTIMIZATION: Use has_value() for optional instead of nullptr check
if (!actor.body.leftThumbMedial.has_value() || !actor.body.leftThumbDistal.has_value() || !actor.body.leftThumbTip.has_value()) {
return false;
}
return true;
} catch (...) {
return false;
}
}
bool RokokoDataParser::ExtractFingerData(const RokokoData::LiveFrame_v4& frame,
std::vector<RokokoData::ActorJointFrame>& leftHandFingers,
std::vector<RokokoData::ActorJointFrame>& rightHandFingers)
{
try {
leftHandFingers.clear();
rightHandFingers.clear();
if (frame.scene.actors.empty()) {
return false;
}
const auto& actor = frame.scene.actors[0];
// ✅ OPTIMIZATION: Use has_value() for optional instead of implicit bool conversion
// 왼손 데이터 추출 (20개 관절)
if (actor.body.leftThumbProximal.has_value()) leftHandFingers.push_back(*actor.body.leftThumbProximal);
if (actor.body.leftThumbMedial.has_value()) leftHandFingers.push_back(*actor.body.leftThumbMedial);
if (actor.body.leftThumbDistal.has_value()) leftHandFingers.push_back(*actor.body.leftThumbDistal);
if (actor.body.leftThumbTip.has_value()) leftHandFingers.push_back(*actor.body.leftThumbTip);
if (actor.body.leftIndexProximal.has_value()) leftHandFingers.push_back(*actor.body.leftIndexProximal);
if (actor.body.leftIndexMedial.has_value()) leftHandFingers.push_back(*actor.body.leftIndexMedial);
if (actor.body.leftIndexDistal.has_value()) leftHandFingers.push_back(*actor.body.leftIndexDistal);
if (actor.body.leftIndexTip.has_value()) leftHandFingers.push_back(*actor.body.leftIndexTip);
if (actor.body.leftMiddleProximal.has_value()) leftHandFingers.push_back(*actor.body.leftMiddleProximal);
if (actor.body.leftMiddleMedial.has_value()) leftHandFingers.push_back(*actor.body.leftMiddleMedial);
if (actor.body.leftMiddleDistal.has_value()) leftHandFingers.push_back(*actor.body.leftMiddleDistal);
if (actor.body.leftMiddleTip.has_value()) leftHandFingers.push_back(*actor.body.leftMiddleTip);
if (actor.body.leftRingProximal.has_value()) leftHandFingers.push_back(*actor.body.leftRingProximal);
if (actor.body.leftRingMedial.has_value()) leftHandFingers.push_back(*actor.body.leftRingMedial);
if (actor.body.leftRingDistal.has_value()) leftHandFingers.push_back(*actor.body.leftRingDistal);
if (actor.body.leftRingTip.has_value()) leftHandFingers.push_back(*actor.body.leftRingTip);
if (actor.body.leftLittleProximal.has_value()) leftHandFingers.push_back(*actor.body.leftLittleProximal);
if (actor.body.leftLittleMedial.has_value()) leftHandFingers.push_back(*actor.body.leftLittleMedial);
if (actor.body.leftLittleDistal.has_value()) leftHandFingers.push_back(*actor.body.leftLittleDistal);
if (actor.body.leftLittleTip.has_value()) leftHandFingers.push_back(*actor.body.leftLittleTip);
// 오른손 데이터 추출 (20개 관절)
if (actor.body.rightThumbProximal.has_value()) rightHandFingers.push_back(*actor.body.rightThumbProximal);
if (actor.body.rightThumbMedial.has_value()) rightHandFingers.push_back(*actor.body.rightThumbMedial);
if (actor.body.rightThumbDistal.has_value()) rightHandFingers.push_back(*actor.body.rightThumbDistal);
if (actor.body.rightThumbTip.has_value()) rightHandFingers.push_back(*actor.body.rightThumbTip);
if (actor.body.rightIndexProximal.has_value()) rightHandFingers.push_back(*actor.body.rightIndexProximal);
if (actor.body.rightIndexMedial.has_value()) rightHandFingers.push_back(*actor.body.rightIndexMedial);
if (actor.body.rightIndexDistal.has_value()) rightHandFingers.push_back(*actor.body.rightIndexDistal);
if (actor.body.rightIndexTip.has_value()) rightHandFingers.push_back(*actor.body.rightIndexTip);
if (actor.body.rightMiddleProximal.has_value()) rightHandFingers.push_back(*actor.body.rightMiddleProximal);
if (actor.body.rightMiddleMedial.has_value()) rightHandFingers.push_back(*actor.body.rightMiddleMedial);
if (actor.body.rightMiddleDistal.has_value()) rightHandFingers.push_back(*actor.body.rightMiddleDistal);
if (actor.body.rightMiddleTip.has_value()) rightHandFingers.push_back(*actor.body.rightMiddleTip);
if (actor.body.rightRingProximal.has_value()) rightHandFingers.push_back(*actor.body.rightRingProximal);
if (actor.body.rightRingMedial.has_value()) rightHandFingers.push_back(*actor.body.rightRingMedial);
if (actor.body.rightRingDistal.has_value()) rightHandFingers.push_back(*actor.body.rightRingDistal);
if (actor.body.rightRingTip.has_value()) rightHandFingers.push_back(*actor.body.rightRingTip);
if (actor.body.rightLittleProximal.has_value()) rightHandFingers.push_back(*actor.body.rightLittleProximal);
if (actor.body.rightLittleMedial.has_value()) rightHandFingers.push_back(*actor.body.rightLittleMedial);
if (actor.body.rightLittleDistal.has_value()) rightHandFingers.push_back(*actor.body.rightLittleDistal);
if (actor.body.rightLittleTip.has_value()) rightHandFingers.push_back(*actor.body.rightLittleTip);
return true;
} catch (...) {
return false;
}
}
bool RokokoDataParser::ParseActorData(const void* actorJson, RokokoData::ActorData& actor)
{
// 현재는 기본 구현만 제공
// 실제 JSON 파싱 라이브러리 사용 시 구현
return true;
}
bool RokokoDataParser::ParseFingerData(const void* fingerJson, RokokoData::ActorJointFrame& finger)
{
// 현재는 기본 구현만 제공
// 실제 JSON 파싱 라이브러리 사용 시 구현
return true;
}
bool RokokoDataParser::ValidateQuaternion(float x, float y, float z, float w)
{
// NaN 체크
if (std::isnan(x) || std::isnan(y) || std::isnan(z) || std::isnan(w)) {
return false;
}
// 무한대 체크
if (std::isinf(x) || std::isinf(y) || std::isinf(z) || std::isinf(w)) {
return false;
}
// 쿼터니언 길이 체크 (정규화된 경우 1.0에 가까워야 함)
float length = std::sqrt(x * x + y * y + z * z + w * w);
if (length < 0.1f || length > 10.0f) {
return false;
}
return true;
}
void RokokoDataParser::NormalizeQuaternion(float& x, float& y, float& z, float& w)
{
float length = std::sqrt(x * x + y * y + z * z + w * w);
if (length > 0.0001f) {
x /= length;
y /= length;
z /= length;
w /= length;
} else {
// 기본값 설정
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 1.0f;
}
}
}

View File

@ -1,104 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* RokokoDataParser class provides JSON parsing functionality for Rokoko glove data.
* This parser handles the LiveFrame_v4 JSON format from Rokoko Studio.
*/
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <optional>
#include <nlohmann/json.hpp>
// Forward declarations for JSON data structures
namespace RokokoData
{
struct Vector3Frame;
struct Vector4Frame;
struct ActorJointFrame;
struct ActorData;
struct LiveFrame_v4;
struct Body;
}
namespace RokokoIntegration
{
class RokokoDataParser
{
public:
/**
* Parses LiveFrame_v4 JSON data
* @param jsonString JSON string to parse
* @param frame Output frame data structure
* @return true if parsing successful
*/
static bool ParseLiveFrame(const std::string& jsonString, RokokoData::LiveFrame_v4& frame);
/**
* Validates parsed frame data
* @param frame Frame data to validate
* @return true if frame data is valid
*/
static bool ValidateFrameData(const RokokoData::LiveFrame_v4& frame);
/**
* Extracts finger joint data from frame
* @param frame Input frame data
* @param leftHandFingers Output left hand finger data
* @param rightHandFingers Output right hand finger data
* @return true if extraction successful
*/
static bool ExtractFingerData(const RokokoData::LiveFrame_v4& frame,
std::vector<RokokoData::ActorJointFrame>& leftHandFingers,
std::vector<RokokoData::ActorJointFrame>& rightHandFingers);
private:
/**
* Parses body frame data from JSON
* @param bodyJson JSON object containing body data
* @param body Output body data structure
*/
static void ParseBodyFrame(const nlohmann::json& bodyJson, RokokoData::Body& body);
/**
* Parses individual finger joint data from JSON
* @param bodyJson JSON object containing body data
* @param jointName Name of the joint to parse
* @param joint Output joint data structure (std::optional for stack allocation)
*/
static void ParseFingerJoint(const nlohmann::json& bodyJson, const std::string& jointName,
std::optional<RokokoData::ActorJointFrame>& joint);
/**
* Parses actor data from JSON
* @param actorJson JSON object containing actor data
* @param actor Output actor data structure
* @return true if parsing successful
*/
static bool ParseActorData(const void* actorJson, RokokoData::ActorData& actor);
/**
* Parses finger joint data from JSON
* @param fingerJson JSON object containing finger data
* @param finger Output finger data structure
* @return true if parsing successful
*/
static bool ParseFingerData(const void* fingerJson, RokokoData::ActorJointFrame& finger);
/**
* Validates quaternion values
* @param x, y, z, w Quaternion components
* @return true if quaternion is valid
*/
static bool ValidateQuaternion(float x, float y, float z, float w);
/**
* Normalizes quaternion values
* @param x, y, z, w Quaternion components (modified in place)
*/
static void NormalizeQuaternion(float& x, float& y, float& z, float& w);
};
}

View File

@ -1,151 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>RokokoGloveDevice_Fixed</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
<ProjectName>RokokoGloveDevice_Fixed</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="GloveDeviceDeveloperConfigDebug.props" Condition="Exists('GloveDeviceDeveloperConfigDebug.props')" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="GloveDeviceDeveloperConfigRelease.props" Condition="Exists('GloveDeviceDeveloperConfigRelease.props')" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LocalDebuggerCommand>C:\Program Files\OptiTrack\Motive\Motive.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LocalDebuggerCommand>C:\Program Files\OptiTrack\Motive\Motive.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<!-- Post-Build 이벤트 비활성화 - DLL을 수동으로 복사하도록 설정 -->
<!--
<ItemDefinitionGroup Condition="!Exists('GloveDeviceDeveloperConfigDebug.props')">
<PostBuildEvent>
<Command>if not exist "C:\Program Files\OptiTrack\Motive\devices" mkdir "C:\Program Files\OptiTrack\Motive\devices"
if exist "$(OutDir)RokokoGloveDevice.dll" copy "$(OutDir)RokokoGloveDevice.dll" "C:\Program Files\OptiTrack\Motive\devices"
if exist "$(OutDir)ExampleGloveData.csv" copy "$(OutDir)ExampleGloveData.csv" "C:\Program Files\OptiTrack\Motive\devices"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
-->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<LanguageStandard>stdcpp17</LanguageStandard>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;ANALOGSYSTEM_IMPORTS;OPTITRACKPERIPHERALEXAMPLE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<AdditionalIncludeDirectories>..\include;..\external;..\external\nlohmann;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ShowProgress>NotSet</ShowProgress>
<AdditionalDependencies>PeripheralImport.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ProjectReference>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<LanguageStandard>stdcpp17</LanguageStandard>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;OPTITRACKPERIPHERALEXAMPLE_EXPORTS;ANALOGSYSTEM_IMPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;..\external;..\external\nlohmann;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>PeripheralImport.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="dllcommon.h" />
<ClInclude Include="ExampleGloveAdapterSingleton.h" />
<ClInclude Include="ExampleGloveDevice.h" />
<ClInclude Include="GloveDeviceBase.h" />
<ClInclude Include="GloveDataFormat.h" />
<ClInclude Include="LZ4Wrapper.h" />
<ClInclude Include="RokokoData.h" />
<ClInclude Include="RokokoDataParser.h" />
<ClInclude Include="RokokoUDPReceiver.h" />
<ClInclude Include="RokokoDataConverter.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</PrecompiledHeader>
</ClCompile>
<ClCompile Include="ExampleGloveAdapterSingleton.cpp" />
<ClCompile Include="ExampleGloveDevice.cpp" />
<ClCompile Include="GloveDeviceBase.cpp" />
<ClCompile Include="LZ4Wrapper.cpp" />
<ClCompile Include="RokokoUDPReceiver.cpp" />
<ClCompile Include="RokokoDataParser.cpp" />
<ClCompile Include="RokokoDataConverter.cpp" />
</ItemGroup>
<ItemGroup>
<Text Include="readme.txt" />
</ItemGroup>
<ItemGroup>
<CopyFileToFolders Include="ExampleGloveData.csv">
<FileType>Document</FileType>
</CopyFileToFolders>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,90 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="dllcommon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ExampleGloveDevice.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GloveDataFormat.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GloveDeviceBase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="HardwareSimulator.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ExampleGloveAdapterSingleton.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LZ4Wrapper.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="lz4.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RokokoData.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RokokoDataParser.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RokokoUDPReceiver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="RokokoDataConverter.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ExampleGloveDevice.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GloveDeviceBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="HardwareSimulator.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ExampleGloveAdapterSingleton.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LZ4Wrapper.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="lz4.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RokokoUDPReceiver.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="RokokoDataConverter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Text Include="readme.txt" />
</ItemGroup>
<ItemGroup>
<CopyFileToFolders Include="ExampleGloveData.csv" />
</ItemGroup>
</Project>

View File

@ -1,307 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration - FIXED VERSION
//======================================================================================================
/**
* FIXES APPLIED:
* 1. WSACleanup duplicate calls - Added reference counting
* 2. CPU 100% usage - Added select() with timeout instead of busy-wait
* 3. Thread safety - Using lock_guard consistently
*/
#include "RokokoUDPReceiver.h"
#include <chrono>
#include <sstream>
#include <iostream>
namespace RokokoIntegration
{
// Static members for WSA reference counting
std::atomic<int> RokokoUDPReceiver::s_wsaRefCount{0};
std::mutex RokokoUDPReceiver::s_wsaMutex;
RokokoUDPReceiver::RokokoUDPReceiver()
: mSocket(INVALID_SOCKET)
, mIsRunning(false)
, mIsListening(false)
, mPacketsReceived(0)
, mBytesReceived(0)
, mLastPacketTime(0.0)
, mPort(14043)
, mBufferSize(65000)
, mWsaInitialized(false)
{
}
RokokoUDPReceiver::~RokokoUDPReceiver()
{
StopListening();
CloseSocket();
}
// FIX 1: WSA Reference Counting
bool RokokoUDPReceiver::InitializeWSA()
{
std::lock_guard<std::mutex> lock(s_wsaMutex);
if (s_wsaRefCount == 0) {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
return false;
}
}
s_wsaRefCount++;
mWsaInitialized = true;
return true;
}
void RokokoUDPReceiver::CleanupWSA()
{
if (!mWsaInitialized) {
return;
}
std::lock_guard<std::mutex> lock(s_wsaMutex);
s_wsaRefCount--;
if (s_wsaRefCount == 0) {
WSACleanup();
}
mWsaInitialized = false;
}
bool RokokoUDPReceiver::Initialize(int port)
{
try {
mPort = port;
// FIX: Use reference-counted WSA initialization
if (!InitializeWSA()) {
SetError("WSAStartup failed");
return false;
}
// UDP 소켓 생성
mSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (mSocket == INVALID_SOCKET) {
SetError("Failed to create UDP socket");
CleanupWSA();
return false;
}
// 소켓 옵션 설정
int sendBufferSize = mBufferSize;
if (setsockopt(mSocket, SOL_SOCKET, SO_SNDBUF,
(char*)&sendBufferSize, sizeof(sendBufferSize)) == SOCKET_ERROR) {
SetError("Failed to set send buffer size");
CloseSocket();
return false;
}
// 주소 구조체 설정
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(mPort);
serverAddr.sin_addr.s_addr = INADDR_ANY;
// 소켓 바인딩
if (bind(mSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::ostringstream oss;
oss << "Failed to bind to port " << mPort << ". Port may be in use.";
SetError(oss.str());
CloseSocket();
return false;
}
// 논블로킹 모드는 select()와 함께 사용
u_long mode = 1;
if (ioctlsocket(mSocket, FIONBIO, &mode) == SOCKET_ERROR) {
SetError("Failed to set non-blocking mode");
CloseSocket();
return false;
}
return true;
} catch (...) {
SetError("Exception during UDP initialization");
return false;
}
}
bool RokokoUDPReceiver::StartListening()
{
if (mSocket == INVALID_SOCKET) {
SetError("UDP socket not initialized");
return false;
}
if (mIsListening) {
SetError("Already listening");
return false;
}
try {
mIsRunning = true;
mIsListening = true;
// 수신 스레드 시작
mReceiveThread = std::thread(&RokokoUDPReceiver::ReceiveThread, this);
return true;
} catch (...) {
SetError("Exception starting receive thread");
mIsRunning = false;
mIsListening = false;
return false;
}
}
void RokokoUDPReceiver::StopListening()
{
mIsRunning = false;
mIsListening = false;
if (mReceiveThread.joinable()) {
mReceiveThread.join();
}
}
void RokokoUDPReceiver::SetDataCallback(std::function<void(const std::vector<uint8_t>&, const std::string&)> callback)
{
mDataCallback = callback;
}
bool RokokoUDPReceiver::IsListening() const
{
return mIsListening;
}
bool RokokoUDPReceiver::IsConnected() const
{
return mIsListening && mPacketsReceived > 0;
}
std::string RokokoUDPReceiver::GetLastError() const
{
std::lock_guard<std::mutex> lock(mErrorMutex);
return mLastError;
}
void RokokoUDPReceiver::GetStatistics(uint64_t& packetsReceived, uint64_t& bytesReceived, double& lastPacketTime) const
{
std::lock_guard<std::mutex> lock(mStatsMutex);
packetsReceived = mPacketsReceived;
bytesReceived = mBytesReceived;
lastPacketTime = mLastPacketTime;
}
// FIX 2: Use select() to prevent CPU 100% usage
void RokokoUDPReceiver::ReceiveThread()
{
std::vector<uint8_t> buffer(mBufferSize);
while (mIsRunning) {
try {
// ✅ FIX: Use select() to wait for data efficiently
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(mSocket, &readSet);
// Timeout: 100ms (10 checks per second)
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000; // 100ms
int selectResult = select(0, &readSet, nullptr, nullptr, &timeout);
if (selectResult > 0 && FD_ISSET(mSocket, &readSet)) {
// Data available - receive it
struct sockaddr_in senderAddr;
int senderAddrSize = sizeof(senderAddr);
int bytesReceived = recvfrom(mSocket,
reinterpret_cast<char*>(buffer.data()),
mBufferSize,
0,
(struct sockaddr*)&senderAddr,
&senderAddrSize);
if (bytesReceived > 0) {
// 발신자 IP 주소 추출
char senderIP[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &senderAddr.sin_addr, senderIP, INET_ADDRSTRLEN);
std::string senderIPStr(senderIP);
// 데이터 처리
ProcessIncomingData(buffer.data(), bytesReceived, senderIPStr);
// 통계 업데이트
UpdateStatistics(bytesReceived);
}
} else if (selectResult == SOCKET_ERROR) {
int error = WSAGetLastError();
std::ostringstream oss;
oss << "select() error: " << error;
SetError(oss.str());
break;
}
// selectResult == 0 means timeout - just continue loop (no busy-wait!)
} catch (...) {
SetError("Exception in receive thread");
break;
}
}
mIsListening = false;
}
void RokokoUDPReceiver::ProcessIncomingData(const uint8_t* data, int size, const std::string& senderIP)
{
if (mDataCallback && data && size > 0) {
try {
// 데이터를 벡터로 복사
std::vector<uint8_t> dataCopy(data, data + size);
// 콜백 호출
mDataCallback(dataCopy, senderIP);
} catch (...) {
SetError("Exception in data callback");
}
}
}
void RokokoUDPReceiver::SetError(const std::string& error)
{
std::lock_guard<std::mutex> lock(mErrorMutex);
mLastError = error;
// 에러 로깅 (OptiTrack에서 확인 가능)
std::cerr << "[RokokoUDPReceiver] Error: " << error << std::endl;
}
void RokokoUDPReceiver::UpdateStatistics(int packetSize)
{
std::lock_guard<std::mutex> lock(mStatsMutex);
mPacketsReceived++;
mBytesReceived += packetSize;
mLastPacketTime = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count() / 1000.0;
}
void RokokoUDPReceiver::CloseSocket()
{
if (mSocket != INVALID_SOCKET) {
closesocket(mSocket);
mSocket = INVALID_SOCKET;
}
// FIX: Use reference-counted cleanup
CleanupWSA();
}
}

View File

@ -1,154 +0,0 @@
//======================================================================================================
// Copyright 2025, Rokoko Glove OptiTrack Integration
//======================================================================================================
/**
* RokokoUDPReceiver class provides UDP communication functionality for receiving Rokoko glove data.
* This receiver handles UDP socket communication and data reception from Rokoko Studio.
*/
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <functional>
#include <thread>
#include <vector>
#include <atomic>
#include <mutex>
namespace RokokoIntegration
{
class RokokoUDPReceiver
{
public:
/**
* Constructor
*/
RokokoUDPReceiver();
/**
* Destructor
*/
~RokokoUDPReceiver();
/**
* Initializes UDP receiver
* @param port UDP port to listen on (default: 14043)
* @return true if initialization successful
*/
bool Initialize(int port = 14043);
/**
* Starts listening for UDP data
* @return true if started successfully
*/
bool StartListening();
/**
* Stops listening for UDP data
*/
void StopListening();
/**
* Sets callback function for received data
* @param callback Function to call when data is received
*/
void SetDataCallback(std::function<void(const std::vector<uint8_t>&, const std::string&)> callback);
/**
* Checks if receiver is currently listening
* @return true if listening
*/
bool IsListening() const;
/**
* Gets the current connection status
* @return true if connected and receiving data
*/
bool IsConnected() const;
/**
* Gets the last error message
* @return Error message string
*/
std::string GetLastError() const;
/**
* Gets connection statistics
* @param packetsReceived Number of packets received
* @param bytesReceived Total bytes received
* @param lastPacketTime Timestamp of last packet
*/
void GetStatistics(uint64_t& packetsReceived, uint64_t& bytesReceived, double& lastPacketTime) const;
private:
// UDP socket
SOCKET mSocket;
// Thread management
std::thread mReceiveThread;
std::atomic<bool> mIsRunning;
std::atomic<bool> mIsListening;
// Data callback
std::function<void(const std::vector<uint8_t>&, const std::string&)> mDataCallback;
// Statistics
mutable std::mutex mStatsMutex;
uint64_t mPacketsReceived;
uint64_t mBytesReceived;
double mLastPacketTime;
// Error handling
mutable std::mutex mErrorMutex;
std::string mLastError;
// Configuration
int mPort;
int mBufferSize;
/**
* Main receive thread function
*/
void ReceiveThread();
/**
* Processes incoming UDP data
* @param data Received data
* @param size Size of received data
* @param senderIP IP address of sender
*/
void ProcessIncomingData(const uint8_t* data, int size, const std::string& senderIP);
/**
* Sets error message
* @param error Error message
*/
void SetError(const std::string& error);
/**
* Updates statistics
* @param packetSize Size of received packet
*/
void UpdateStatistics(int packetSize);
/**
* Closes UDP socket
*/
void CloseSocket();
// WSA reference counting (FIX: Prevent duplicate WSACleanup calls)
static std::atomic<int> s_wsaRefCount;
static std::mutex s_wsaMutex;
bool mWsaInitialized;
/**
* Initialize WSA with reference counting
*/
bool InitializeWSA();
/**
* Cleanup WSA with reference counting
*/
void CleanupWSA();
};
}

View File

@ -1,12 +0,0 @@
//======================================================================================================
// Copyright 2016, NaturalPoint Inc.
//======================================================================================================
// windows
#include <SDKDDKVer.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

View File

@ -1,103 +0,0 @@
//======================================================================================================
// Copyright 2016, NaturalPoint Inc.
//======================================================================================================
//
// dllmain.cpp : Defines the entry point for the DLL application.
//
#include "dllcommon.h"
// stl
#include <list>
#include <memory>
using namespace std;
// OptiTrack Peripheral Device API
#include "IDeviceManager.h"
using namespace AnalogSystem;
// local devices
#include "ExampleGloveDevice.h"
using namespace OptiTrackPluginDevices;
int hostVersionMajor, hostVersionMinor, hostVersionRevision;
#ifdef OPTITRACKPERIPHERALEXAMPLE_EXPORTS
#define OPTITRACKPERIPHERALEXAMPLE_API __declspec(dllexport)
#else
#define OPTITRACKPERIPHERALEXAMPLE_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
using namespace OptiTrackPluginDevices;
using namespace ExampleDevice;
/**
* Defines the version information of the plugin DLL within Motive.
*/
OPTITRACKPERIPHERALEXAMPLE_API void DLLVersion(int hostMajor, int hostMinor, int hostRevision, int& dllMajor, int& dllMinor, int& dllRevision)
{
hostVersionMajor = hostMajor;
hostVersionMajor = hostMinor;
hostVersionMajor = hostRevision;
// report this peripheral device's version to host
dllMajor = 1;
dllMinor = 0;
dllRevision = 0;
}
/**
* Motive calls the following method on application start up. This register device factories with Motive
* so that the device can be instantiated when it's ready (1 factory per device)
*/
OPTITRACKPERIPHERALEXAMPLE_API int DLLEnumerateDeviceFactories(IDeviceManager* pDeviceManager)
{
list<unique_ptr<IDeviceFactory>> availDFs;
ExampleDevice::ExampleGlove_EnumerateDeviceFactories(pDeviceManager, availDFs);
for (list<unique_ptr<IDeviceFactory>>::iterator iter = availDFs.begin(); iter != availDFs.end(); iter++) {
// transfers ownership of device factory to host
pDeviceManager->AddDevice(std::move(*iter));
}
return (int)availDFs.size();
}
/**
* The following method gets called on application shutdown. Proper shutdown should happen here;
* including termination of the process of the DLL and memory unload.
*/
OPTITRACKPERIPHERALEXAMPLE_API int PluginDLLUnload(IDeviceManager* pDeviceManager)
{
// OPTIONAL: perform device DLL shutdown here
ExampleGlove_Shutdown();
return 0;
}
#ifdef __cplusplus
}
#endif
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,842 +0,0 @@
/*
* LZ4 - Fast LZ compression algorithm
* Header File
* Copyright (C) 2011-2020, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
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.
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.
You can contact the author at :
- LZ4 homepage : http://www.lz4.org
- LZ4 source repository : https://github.com/lz4/lz4
*/
#if defined (__cplusplus)
extern "C" {
#endif
#ifndef LZ4_H_2983827168210
#define LZ4_H_2983827168210
/* --- Dependency --- */
#include <stddef.h> /* size_t */
/**
Introduction
LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core,
scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
The LZ4 compression library provides in-memory compression and decompression functions.
It gives full buffer control to user.
Compression can be done in:
- a single step (described as Simple Functions)
- a single step, reusing a context (described in Advanced Functions)
- unbounded multiple steps (described as Streaming compression)
lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md).
Decompressing such a compressed block requires additional metadata.
Exact metadata depends on exact decompression function.
For the typical case of LZ4_decompress_safe(),
metadata includes block's compressed size, and maximum bound of decompressed size.
Each application is free to encode and pass such metadata in whichever way it wants.
lz4.h only handle blocks, it can not generate Frames.
Blocks are different from Frames (doc/lz4_Frame_format.md).
Frames bundle both blocks and metadata in a specified manner.
Embedding metadata is required for compressed data to be self-contained and portable.
Frame format is delivered through a companion API, declared in lz4frame.h.
The `lz4` CLI can only manage frames.
*/
/*^***************************************************************
* Export parameters
*****************************************************************/
/*
* LZ4_DLL_EXPORT :
* Enable exporting of functions when building a Windows DLL
* LZ4LIB_VISIBILITY :
* Control library symbols visibility.
*/
#ifndef LZ4LIB_VISIBILITY
# if defined(__GNUC__) && (__GNUC__ >= 4)
# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default")))
# else
# define LZ4LIB_VISIBILITY
# endif
#endif
#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY
#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
#else
# define LZ4LIB_API LZ4LIB_VISIBILITY
#endif
/*! LZ4_FREESTANDING :
* When this macro is set to 1, it enables "freestanding mode" that is
* suitable for typical freestanding environment which doesn't support
* standard C library.
*
* - LZ4_FREESTANDING is a compile-time switch.
* - It requires the following macros to be defined:
* LZ4_memcpy, LZ4_memmove, LZ4_memset.
* - It only enables LZ4/HC functions which don't use heap.
* All LZ4F_* functions are not supported.
* - See tests/freestanding.c to check its basic setup.
*/
#if defined(LZ4_FREESTANDING) && (LZ4_FREESTANDING == 1)
# define LZ4_HEAPMODE 0
# define LZ4HC_HEAPMODE 0
# define LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION 1
# if !defined(LZ4_memcpy)
# error "LZ4_FREESTANDING requires macro 'LZ4_memcpy'."
# endif
# if !defined(LZ4_memset)
# error "LZ4_FREESTANDING requires macro 'LZ4_memset'."
# endif
# if !defined(LZ4_memmove)
# error "LZ4_FREESTANDING requires macro 'LZ4_memmove'."
# endif
#elif ! defined(LZ4_FREESTANDING)
# define LZ4_FREESTANDING 0
#endif
/*------ Version ------*/
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
#define LZ4_VERSION_MINOR 9 /* for new (non-breaking) interface capabilities */
#define LZ4_VERSION_RELEASE 4 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
#define LZ4_QUOTE(str) #str
#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) /* requires v1.7.3+ */
LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version; requires v1.3.0+ */
LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; useful to check dll version; requires v1.7.5+ */
/*-************************************
* Tuning parameter
**************************************/
#define LZ4_MEMORY_USAGE_MIN 10
#define LZ4_MEMORY_USAGE_DEFAULT 14
#define LZ4_MEMORY_USAGE_MAX 20
/*!
* LZ4_MEMORY_USAGE :
* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; )
* Increasing memory usage improves compression ratio, at the cost of speed.
* Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality.
* Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
*/
#ifndef LZ4_MEMORY_USAGE
# define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
#endif
#if (LZ4_MEMORY_USAGE < LZ4_MEMORY_USAGE_MIN)
# error "LZ4_MEMORY_USAGE is too small !"
#endif
#if (LZ4_MEMORY_USAGE > LZ4_MEMORY_USAGE_MAX)
# error "LZ4_MEMORY_USAGE is too large !"
#endif
/*-************************************
* Simple Functions
**************************************/
/*! LZ4_compress_default() :
* Compresses 'srcSize' bytes from buffer 'src'
* into already allocated 'dst' buffer of size 'dstCapacity'.
* Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize).
* It also runs faster, so it's a recommended setting.
* If the function cannot compress 'src' into a more limited 'dst' budget,
* compression stops *immediately*, and the function result is zero.
* In which case, 'dst' content is undefined (invalid).
* srcSize : max supported value is LZ4_MAX_INPUT_SIZE.
* dstCapacity : size of buffer 'dst' (which must be already allocated)
* @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity)
* or 0 if compression fails
* Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer).
*/
LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);
/*! LZ4_decompress_safe() :
* compressedSize : is the exact complete size of the compressed block.
* dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size.
* @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
* If destination buffer is not large enough, decoding will stop and output an error code (negative value).
* If the source stream is detected malformed, the function will stop decoding and return a negative result.
* Note 1 : This function is protected against malicious data packets :
* it will never writes outside 'dst' buffer, nor read outside 'source' buffer,
* even if the compressed block is maliciously modified to order the decoder to do these actions.
* In such case, the decoder stops immediately, and considers the compressed block malformed.
* Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them.
* The implementation is free to send / store / derive this information in whichever way is most beneficial.
* If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead.
*/
LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity);
/*-************************************
* Advanced Functions
**************************************/
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
/*! LZ4_compressBound() :
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
This function is primarily useful for memory allocation purposes (destination buffer size).
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize)
inputSize : max supported value is LZ4_MAX_INPUT_SIZE
return : maximum output size in a "worst case" scenario
or 0, if input size is incorrect (too large or negative)
*/
LZ4LIB_API int LZ4_compressBound(int inputSize);
/*! LZ4_compress_fast() :
Same as LZ4_compress_default(), but allows selection of "acceleration" factor.
The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
An acceleration value of "1" is the same as regular LZ4_compress_default()
Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c).
Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c).
*/
LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_compress_fast_extState() :
* Same as LZ4_compress_fast(), using an externally allocated memory space for its state.
* Use LZ4_sizeofState() to know how much memory must be allocated,
* and allocate it on 8-bytes boundaries (using `malloc()` typically).
* Then, provide this buffer as `void* state` to compression function.
*/
LZ4LIB_API int LZ4_sizeofState(void);
LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_compress_destSize() :
* Reverse the logic : compresses as much data as possible from 'src' buffer
* into already allocated buffer 'dst', of size >= 'targetDestSize'.
* This function either compresses the entire 'src' content into 'dst' if it's large enough,
* or fill 'dst' buffer completely with as much data as possible from 'src'.
* note: acceleration parameter is fixed to "default".
*
* *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
* New value is necessarily <= input value.
* @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
* or 0 if compression fails.
*
* Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):
* the produced compressed content could, in specific circumstances,
* require to be decompressed into a destination buffer larger
* by at least 1 byte than the content to decompress.
* If an application uses `LZ4_compress_destSize()`,
* it's highly recommended to update liblz4 to v1.9.2 or better.
* If this can't be done or ensured,
* the receiving decompression function should provide
* a dstCapacity which is > decompressedSize, by at least 1 byte.
* See https://github.com/lz4/lz4/issues/859 for details
*/
LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
/*! LZ4_decompress_safe_partial() :
* Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',
* into destination buffer 'dst' of size 'dstCapacity'.
* Up to 'targetOutputSize' bytes will be decoded.
* The function stops decoding on reaching this objective.
* This can be useful to boost performance
* whenever only the beginning of a block is required.
*
* @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize)
* If source stream is detected malformed, function returns a negative result.
*
* Note 1 : @return can be < targetOutputSize, if compressed block contains less data.
*
* Note 2 : targetOutputSize must be <= dstCapacity
*
* Note 3 : this function effectively stops decoding on reaching targetOutputSize,
* so dstCapacity is kind of redundant.
* This is because in older versions of this function,
* decoding operation would still write complete sequences.
* Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize,
* it could write more bytes, though only up to dstCapacity.
* Some "margin" used to be required for this operation to work properly.
* Thankfully, this is no longer necessary.
* The function nonetheless keeps the same signature, in an effort to preserve API compatibility.
*
* Note 4 : If srcSize is the exact size of the block,
* then targetOutputSize can be any value,
* including larger than the block's decompressed size.
* The function will, at most, generate block's decompressed size.
*
* Note 5 : If srcSize is _larger_ than block's compressed size,
* then targetOutputSize **MUST** be <= block's decompressed size.
* Otherwise, *silent corruption will occur*.
*/
LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity);
/*-*********************************************
* Streaming Compression Functions
***********************************************/
typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
/**
Note about RC_INVOKED
- RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio).
https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros
- Since rc.exe is a legacy compiler, it truncates long symbol (> 30 chars)
and reports warning "RC4011: identifier truncated".
- To eliminate the warning, we surround long preprocessor symbol with
"#if !defined(RC_INVOKED) ... #endif" block that means
"skip this block when rc.exe is trying to read it".
*/
#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
LZ4LIB_API LZ4_stream_t* LZ4_createStream(void);
LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr);
#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
#endif
/*! LZ4_resetStream_fast() : v1.9.0+
* Use this to prepare an LZ4_stream_t for a new chain of dependent blocks
* (e.g., LZ4_compress_fast_continue()).
*
* An LZ4_stream_t must be initialized once before usage.
* This is automatically done when created by LZ4_createStream().
* However, should the LZ4_stream_t be simply declared on stack (for example),
* it's necessary to initialize it first, using LZ4_initStream().
*
* After init, start any new stream with LZ4_resetStream_fast().
* A same LZ4_stream_t can be re-used multiple times consecutively
* and compress multiple streams,
* provided that it starts each new stream with LZ4_resetStream_fast().
*
* LZ4_resetStream_fast() is much faster than LZ4_initStream(),
* but is not compatible with memory regions containing garbage data.
*
* Note: it's only useful to call LZ4_resetStream_fast()
* in the context of streaming compression.
* The *extState* functions perform their own resets.
* Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive.
*/
LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
/*! LZ4_loadDict() :
* Use this function to reference a static dictionary into LZ4_stream_t.
* The dictionary must remain available during compression.
* LZ4_loadDict() triggers a reset, so any previous data will be forgotten.
* The same dictionary will have to be loaded on decompression side for successful decoding.
* Dictionary are useful for better compression of small data (KB range).
* While LZ4 accept any input as dictionary,
* results are generally better when using Zstandard's Dictionary Builder.
* Loading a size of 0 is allowed, and is the same as reset.
* @return : loaded dictionary size, in bytes (necessarily <= 64 KB)
*/
LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
/*! LZ4_compress_fast_continue() :
* Compress 'src' content using data from previously compressed blocks, for better compression ratio.
* 'dst' buffer must be already allocated.
* If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
*
* @return : size of compressed block
* or 0 if there is an error (typically, cannot fit into 'dst').
*
* Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block.
* Each block has precise boundaries.
* Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata.
* It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together.
*
* Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory !
*
* Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB.
* Make sure that buffers are separated, by at least one byte.
* This construction ensures that each block only depends on previous block.
*
* Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB.
*
* Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed.
*/
LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_saveDict() :
* If last 64KB data cannot be guaranteed to remain available at its current memory location,
* save it into a safer place (char* safeBuffer).
* This is schematically equivalent to a memcpy() followed by LZ4_loadDict(),
* but is much faster, because LZ4_saveDict() doesn't need to rebuild tables.
* @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error.
*/
LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize);
/*-**********************************************
* Streaming Decompression Functions
* Bufferless synchronous API
************************************************/
typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */
/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() :
* creation / destruction of streaming decompression tracking context.
* A tracking context can be re-used multiple times.
*/
#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);
LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
#endif
/*! LZ4_setStreamDecode() :
* An LZ4_streamDecode_t context can be allocated once and re-used multiple times.
* Use this function to start decompression of a new stream of blocks.
* A dictionary can optionally be set. Use NULL or size 0 for a reset order.
* Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.
* @return : 1 if OK, 0 if error
*/
LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
/*! LZ4_decoderRingBufferSize() : v1.8.2+
* Note : in a ring buffer scenario (optional),
* blocks are presumed decompressed next to each other
* up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize),
* at which stage it resumes from beginning of ring buffer.
* When setting such a ring buffer for streaming decompression,
* provides the minimum size of this ring buffer
* to be compatible with any source respecting maxBlockSize condition.
* @return : minimum ring buffer size,
* or 0 if there is an error (invalid maxBlockSize).
*/
LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */
/*! LZ4_decompress_*_continue() :
* These decoding functions allow decompression of consecutive blocks in "streaming" mode.
* A block is an unsplittable entity, it must be presented entirely to a decompression function.
* Decompression functions only accepts one block at a time.
* The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
* If less than 64KB of data has been decoded, all the data must be present.
*
* Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
* - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize).
* maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes.
* In which case, encoding and decoding buffers do not need to be synchronized.
* Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize.
* - Synchronized mode :
* Decompression buffer size is _exactly_ the same as compression buffer size,
* and follows exactly same update rule (block boundaries at same positions),
* and decoding function is provided with exact decompressed size of each block (exception for last block of the stream),
* _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB).
* - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes.
* In which case, encoding and decoding buffers do not need to be synchronized,
* and encoding ring buffer can have any size, including small ones ( < 64 KB).
*
* Whenever these conditions are not possible,
* save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression,
* then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block.
*/
LZ4LIB_API int
LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode,
const char* src, char* dst,
int srcSize, int dstCapacity);
/*! LZ4_decompress_*_usingDict() :
* These decoding functions work the same as
* a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
* They are stand-alone, and don't need an LZ4_streamDecode_t structure.
* Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
* Performance tip : Decompression speed can be substantially increased
* when dst == dictStart + dictSize.
*/
LZ4LIB_API int
LZ4_decompress_safe_usingDict(const char* src, char* dst,
int srcSize, int dstCapacity,
const char* dictStart, int dictSize);
LZ4LIB_API int
LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
int compressedSize,
int targetOutputSize, int maxOutputSize,
const char* dictStart, int dictSize);
#endif /* LZ4_H_2983827168210 */
/*^*************************************
* !!!!!! STATIC LINKING ONLY !!!!!!
***************************************/
/*-****************************************************************************
* Experimental section
*
* Symbols declared in this section must be considered unstable. Their
* signatures or semantics may change, or they may be removed altogether in the
* future. They are therefore only safe to depend on when the caller is
* statically linked against the library.
*
* To protect against unsafe usage, not only are the declarations guarded,
* the definitions are hidden by default
* when building LZ4 as a shared/dynamic library.
*
* In order to access these declarations,
* define LZ4_STATIC_LINKING_ONLY in your application
* before including LZ4's headers.
*
* In order to make their implementations accessible dynamically, you must
* define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library.
******************************************************************************/
#ifdef LZ4_STATIC_LINKING_ONLY
#ifndef LZ4_STATIC_3504398509
#define LZ4_STATIC_3504398509
#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS
#define LZ4LIB_STATIC_API LZ4LIB_API
#else
#define LZ4LIB_STATIC_API
#endif
/*! LZ4_compress_fast_extState_fastReset() :
* A variant of LZ4_compress_fast_extState().
*
* Using this variant avoids an expensive initialization step.
* It is only safe to call if the state buffer is known to be correctly initialized already
* (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized").
* From a high level, the difference is that
* this function initializes the provided state with a call to something like LZ4_resetStream_fast()
* while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream().
*/
LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
/*! LZ4_attach_dictionary() :
* This is an experimental API that allows
* efficient use of a static dictionary many times.
*
* Rather than re-loading the dictionary buffer into a working context before
* each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
* working LZ4_stream_t, this function introduces a no-copy setup mechanism,
* in which the working stream references the dictionary stream in-place.
*
* Several assumptions are made about the state of the dictionary stream.
* Currently, only streams which have been prepared by LZ4_loadDict() should
* be expected to work.
*
* Alternatively, the provided dictionaryStream may be NULL,
* in which case any existing dictionary stream is unset.
*
* If a dictionary is provided, it replaces any pre-existing stream history.
* The dictionary contents are the only history that can be referenced and
* logically immediately precede the data compressed in the first subsequent
* compression call.
*
* The dictionary will only remain attached to the working stream through the
* first compression call, at the end of which it is cleared. The dictionary
* stream (and source buffer) must remain in-place / accessible / unchanged
* through the completion of the first compression call on the stream.
*/
LZ4LIB_STATIC_API void
LZ4_attach_dictionary(LZ4_stream_t* workingStream,
const LZ4_stream_t* dictionaryStream);
/*! In-place compression and decompression
*
* It's possible to have input and output sharing the same buffer,
* for highly constrained memory environments.
* In both cases, it requires input to lay at the end of the buffer,
* and decompression to start at beginning of the buffer.
* Buffer size must feature some margin, hence be larger than final size.
*
* |<------------------------buffer--------------------------------->|
* |<-----------compressed data--------->|
* |<-----------decompressed size------------------>|
* |<----margin---->|
*
* This technique is more useful for decompression,
* since decompressed size is typically larger,
* and margin is short.
*
* In-place decompression will work inside any buffer
* which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize).
* This presumes that decompressedSize > compressedSize.
* Otherwise, it means compression actually expanded data,
* and it would be more efficient to store such data with a flag indicating it's not compressed.
* This can happen when data is not compressible (already compressed, or encrypted).
*
* For in-place compression, margin is larger, as it must be able to cope with both
* history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX,
* and data expansion, which can happen when input is not compressible.
* As a consequence, buffer size requirements are much higher,
* and memory savings offered by in-place compression are more limited.
*
* There are ways to limit this cost for compression :
* - Reduce history size, by modifying LZ4_DISTANCE_MAX.
* Note that it is a compile-time constant, so all compressions will apply this limit.
* Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX,
* so it's a reasonable trick when inputs are known to be small.
* - Require the compressor to deliver a "maximum compressed size".
* This is the `dstCapacity` parameter in `LZ4_compress*()`.
* When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail,
* in which case, the return code will be 0 (zero).
* The caller must be ready for these cases to happen,
* and typically design a backup scheme to send data uncompressed.
* The combination of both techniques can significantly reduce
* the amount of margin required for in-place compression.
*
* In-place compression can work in any buffer
* which size is >= (maxCompressedSize)
* with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success.
* LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX,
* so it's possible to reduce memory requirements by playing with them.
*/
#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize) (((compressedSize) >> 8) + 32)
#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize) ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize)) /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */
#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */
# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */
#endif
#define LZ4_COMPRESS_INPLACE_MARGIN (LZ4_DISTANCE_MAX + 32) /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */
#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize) ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN) /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */
#endif /* LZ4_STATIC_3504398509 */
#endif /* LZ4_STATIC_LINKING_ONLY */
#ifndef LZ4_H_98237428734687
#define LZ4_H_98237428734687
/*-************************************************************
* Private Definitions
**************************************************************
* Do not use these definitions directly.
* They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
* Accessing members will expose user code to API and/or ABI break in future versions of the library.
**************************************************************/
#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
# include <stdint.h>
typedef int8_t LZ4_i8;
typedef uint8_t LZ4_byte;
typedef uint16_t LZ4_u16;
typedef uint32_t LZ4_u32;
#else
typedef signed char LZ4_i8;
typedef unsigned char LZ4_byte;
typedef unsigned short LZ4_u16;
typedef unsigned int LZ4_u32;
#endif
/*! LZ4_stream_t :
* Never ever use below internal definitions directly !
* These definitions are not API/ABI safe, and may change in future versions.
* If you need static allocation, declare or allocate an LZ4_stream_t object.
**/
typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
struct LZ4_stream_t_internal {
LZ4_u32 hashTable[LZ4_HASH_SIZE_U32];
const LZ4_byte* dictionary;
const LZ4_stream_t_internal* dictCtx;
LZ4_u32 currentOffset;
LZ4_u32 tableType;
LZ4_u32 dictSize;
/* Implicit padding to ensure structure is aligned */
};
#define LZ4_STREAM_MINSIZE ((1UL << LZ4_MEMORY_USAGE) + 32) /* static size, for inter-version compatibility */
union LZ4_stream_u {
char minStateSize[LZ4_STREAM_MINSIZE];
LZ4_stream_t_internal internal_donotuse;
}; /* previously typedef'd to LZ4_stream_t */
/*! LZ4_initStream() : v1.9.0+
* An LZ4_stream_t structure must be initialized at least once.
* This is automatically done when invoking LZ4_createStream(),
* but it's not when the structure is simply declared on stack (for example).
*
* Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t.
* It can also initialize any arbitrary buffer of sufficient size,
* and will @return a pointer of proper type upon initialization.
*
* Note : initialization fails if size and alignment conditions are not respected.
* In which case, the function will @return NULL.
* Note2: An LZ4_stream_t structure guarantees correct alignment and size.
* Note3: Before v1.9.0, use LZ4_resetStream() instead
**/
LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);
/*! LZ4_streamDecode_t :
* Never ever use below internal definitions directly !
* These definitions are not API/ABI safe, and may change in future versions.
* If you need static allocation, declare or allocate an LZ4_streamDecode_t object.
**/
typedef struct {
const LZ4_byte* externalDict;
const LZ4_byte* prefixEnd;
size_t extDictSize;
size_t prefixSize;
} LZ4_streamDecode_t_internal;
#define LZ4_STREAMDECODE_MINSIZE 32
union LZ4_streamDecode_u {
char minStateSize[LZ4_STREAMDECODE_MINSIZE];
LZ4_streamDecode_t_internal internal_donotuse;
} ; /* previously typedef'd to LZ4_streamDecode_t */
/*-************************************
* Obsolete Functions
**************************************/
/*! Deprecation warnings
*
* Deprecated functions make the compiler generate a warning when invoked.
* This is meant to invite users to update their source code.
* Should deprecation warnings be a problem, it is generally possible to disable them,
* typically with -Wno-deprecated-declarations for gcc
* or _CRT_SECURE_NO_WARNINGS in Visual.
*
* Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS
* before including the header file.
*/
#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS
# define LZ4_DEPRECATED(message) /* disable deprecation warnings */
#else
# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
# define LZ4_DEPRECATED(message) [[deprecated(message)]]
# elif defined(_MSC_VER)
# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45))
# define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
# elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31)
# define LZ4_DEPRECATED(message) __attribute__((deprecated))
# else
# pragma message("WARNING: LZ4_DEPRECATED needs custom implementation for this compiler")
# define LZ4_DEPRECATED(message) /* disabled */
# endif
#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */
/*! Obsolete compression functions (since v1.7.3) */
LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* src, char* dest, int srcSize);
LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* src, char* dest, int srcSize, int maxOutputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
/*! Obsolete decompression functions (since v1.8.0) */
LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize);
LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize);
/* Obsolete streaming functions (since v1.7.0)
* degraded functionality; do not use!
*
* In order to perform streaming compression, these functions depended on data
* that is no longer tracked in the state. They have been preserved as well as
* possible: using them will still produce a correct output. However, they don't
* actually retain any history between compression calls. The compression ratio
* achieved will therefore be no better than compressing each chunk
* independently.
*/
LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer);
LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void);
LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer);
LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state);
/*! Obsolete streaming decoding functions (since v1.7.0) */
LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize);
LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);
/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) :
* These functions used to be faster than LZ4_decompress_safe(),
* but this is no longer the case. They are now slower.
* This is because LZ4_decompress_fast() doesn't know the input size,
* and therefore must progress more cautiously into the input buffer to not read beyond the end of block.
* On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability.
* As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated.
*
* The last remaining LZ4_decompress_fast() specificity is that
* it can decompress a block without knowing its compressed size.
* Such functionality can be achieved in a more secure manner
* by employing LZ4_decompress_safe_partial().
*
* Parameters:
* originalSize : is the uncompressed size to regenerate.
* `dst` must be already allocated, its size must be >= 'originalSize' bytes.
* @return : number of bytes read from source buffer (== compressed size).
* The function expects to finish at block's end exactly.
* If the source stream is detected malformed, the function stops decoding and returns a negative result.
* note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer.
* However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds.
* Also, since match offsets are not validated, match reads from 'src' may underflow too.
* These issues never happen if input (compressed) data is correct.
* But they may happen if input data is invalid (error or intentional tampering).
* As a consequence, use these functions in trusted environments with trusted data **only**.
*/
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
/*! LZ4_resetStream() :
* An LZ4_stream_t structure must be initialized at least once.
* This is done with LZ4_initStream(), or LZ4_resetStream().
* Consider switching to LZ4_initStream(),
* invoking LZ4_resetStream() will trigger deprecation warnings in the future.
*/
LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr);
#endif /* LZ4_H_98237428734687 */
#if defined (__cplusplus)
}
#endif

Binary file not shown.

Binary file not shown.

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE\EXAMPLEGLOVEDATA.CSV
C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Debug\ExampleGloveData.csv

View File

@ -1 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE\EXAMPLEGLOVEDATA.CSV
C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\X64\DEBUG\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
PlatformToolSet=v142:VCToolArchitecture=Native64Bit:VCToolsVersion=14.29.30133:TargetPlatformVersion=8.1:
Debug|x64|C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\|

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV
C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Debug\ExampleGloveData.csv

View File

@ -1 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV
C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\X64\DEBUG\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
PlatformToolSet=v142:VCToolArchitecture=Native64Bit:VCToolsVersion=14.29.30133:TargetPlatformVersion=8.1:
Debug|x64|C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\|

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Debug\RokokoGloveDevice.dll</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Debug\RokokoGloveDevice_Fixed.dll</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

Binary file not shown.

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV
C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Release\ExampleGloveData.csv

View File

@ -1 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
^C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\ROKOKOGLOVEDEVICE_FIXED\EXAMPLEGLOVEDATA.CSV
C:\USERS\USER\DOCUMENTS\STREAMINGLE_URP\OPTITRACK ROKOKO GLOVE\X64\RELEASE\EXAMPLEGLOVEDATA.CSV

View File

@ -1,2 +0,0 @@
PlatformToolSet=v142:VCToolArchitecture=Native32Bit:VCToolsVersion=14.29.30133:TargetPlatformVersion=8.1:
Release|x64|C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\|

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\user\Documents\Streamingle_URP\Optitrack Rokoko Glove\x64\Release\RokokoGloveDevice_Fixed.dll</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>