EG/vr_test.py
2025-07-16 10:19:34 +08:00

468 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
VR功能测试脚本
测试VR系统的各种功能包括模拟模式和真实VR模式
"""
import sys
import os
from main import MyWorld
def test_basic_vr_functionality():
"""测试基本VR功能"""
print("=== VR基本功能测试 ===")
# 创建世界实例
world = MyWorld()
# 检查VR管理器是否正确初始化
print("✓ VR管理器已创建")
# 检查OpenVR库是否可用
try:
import openvr
print("✓ OpenVR库已安装")
except ImportError:
print("⚠ OpenVR库未安装将使用模拟模式")
# 测试VR初始化会自动回退到模拟模式
print("\n正在测试VR初始化...")
vr_success = world.initializeVR()
if vr_success:
print("✓ VR系统初始化成功")
# 获取VR信息
vr_info = world.getVRInfo()
print(f"\n📊 VR系统信息:")
print(f" - 模式: {vr_info['mode']}")
print(f" - 启用状态: {vr_info['enabled']}")
print(f" - 模拟模式: {vr_info['simulation_mode']}")
print(f" - 渲染尺寸: {vr_info['render_size']}")
print(f" - 控制器数量: {vr_info.get('controllers', 0)}")
# 测试控制器输入
print("\n🎮 测试控制器输入:")
for i in range(2):
controller_input = world.vr_manager.get_controller_input(i)
if controller_input and controller_input.get('connected'):
print(f" 控制器 {i}: 已连接")
print(f" - 扳机: {controller_input['trigger']:.2f}")
print(f" - 握把: {controller_input['grip']:.2f}")
print(f" - 触摸板: ({controller_input['touchpad']['x']:.2f}, {controller_input['touchpad']['y']:.2f})")
else:
print(f" 控制器 {i}: 未连接")
# 测试VR状态
print("\n📊 VR系统状态:")
status = world.getVRStatus()
print(f" - VR启用: {status['vr_enabled']}")
print(f" - 控制器总数: {len(status['controllers'])}")
else:
print("✗ VR系统初始化失败")
return False
# 关闭VR系统
world.shutdownVR()
print("\n✓ VR系统已关闭")
return True
def test_simulation_mode():
"""测试VR模拟模式"""
print("=== VR模拟模式测试 ===")
# 创建世界实例
world = MyWorld()
# 强制启用模拟模式
print("强制启用VR模拟模式...")
vr_success = world.vr_manager.enable_simulation_mode()
if vr_success:
print("✓ VR模拟模式启用成功")
# 获取模拟数据
sim_data = world.vr_manager.get_simulation_data()
if sim_data:
print(f"\n🎮 模拟数据:")
print(f" - 头部位置: {sim_data['head_pose']['position']}")
print(f" - 控制器 0 位置: {sim_data['controller_poses'][0]['position']}")
print(f" - 控制器 1 位置: {sim_data['controller_poses'][1]['position']}")
print(f" - 渲染尺寸: {sim_data['render_size']}")
# 测试更新模拟数据
print(f"\n🔧 测试模拟数据更新:")
new_head_pos = [0.1, 0.1, 1.7]
success = world.vr_manager.update_simulation_data('head_pose', {
'position': new_head_pos,
'rotation': [0, 0, 0, 1]
})
if success:
print(f" ✓ 头部位置更新为: {new_head_pos}")
# 测试控制器输入(模拟)
print(f"\n🎮 模拟控制器输入测试:")
for i in range(2):
controller_input = world.vr_manager.get_controller_input(i)
if controller_input:
print(f" 控制器 {i}:")
print(f" - 连接状态: {controller_input['connected']}")
print(f" - 扳机: {controller_input['trigger']}")
print(f" - 握把: {controller_input['grip']}")
print(f" - 菜单键: {controller_input['menu']}")
else:
print("✗ VR模拟模式启用失败")
return False
# 关闭VR系统
world.vr_manager.shutdown_vr()
print("\n✓ VR模拟模式已关闭")
return True
def test_alvr_streaming():
"""测试ALVR串流功能"""
print("=== ALVR串流测试 ===")
# 创建世界实例
world = MyWorld()
# 初始化VR系统
print("初始化VR系统...")
if not world.initializeVR():
print("✗ VR系统初始化失败")
return False
# 测试ALVR初始化
print("\n正在测试ALVR初始化...")
alvr_success = world.initializeALVR()
if alvr_success:
print("✓ ALVR初始化成功")
# 测试串流状态
print("\n📊 ALVR串流状态:")
status = world.getALVRStreamingStatus()
print(f" - 连接状态: {world.isALVRConnected()}")
print(f" - 串流状态: {world.isALVRStreaming()}")
# 测试串流质量设置
print("\n🎥 测试串流质量设置:")
quality_success = world.setALVRStreamQuality(1920, 1080, 60, 100)
if quality_success:
print(" ✓ 串流质量设置成功: 1920x1080@60fps, 100Mbps")
else:
print(" ⚠ 串流质量设置失败")
# 测试触觉反馈
print("\n🔔 测试触觉反馈:")
for controller_id in range(2):
feedback_success = world.sendHapticFeedback(controller_id, 0.1, 0.5)
if feedback_success:
print(f" ✓ 控制器 {controller_id} 触觉反馈发送成功")
else:
print(f" ⚠ 控制器 {controller_id} 触觉反馈发送失败")
# 测试串流控制
print("\n🎮 测试串流控制:")
start_success = world.startALVRStreaming()
if start_success:
print(" ✓ 串流开始成功")
else:
print(" ⚠ 串流开始失败")
# 等待一下然后停止
import time
time.sleep(1)
stop_success = world.stopALVRStreaming()
if stop_success:
print(" ✓ 串流停止成功")
else:
print(" ⚠ 串流停止失败")
else:
print("⚠ ALVR初始化失败这在没有ALVR服务器时是正常的")
print(" 提示: 要使用ALVR功能请:")
print(" 1. 下载并安装ALVR服务器")
print(" 2. 启动ALVR服务器")
print(" 3. 在Quest头盔上安装并启动ALVR客户端")
# 关闭系统
world.shutdownALVR()
world.shutdownVR()
print("\n✓ ALVR和VR系统已关闭")
return True
def test_vr_gui_control_panel():
"""测试VR GUI控制面板"""
print("=== VR GUI控制面板测试 ===")
try:
from ui.vr_control_panel import VRControlPanel
from PyQt5.QtWidgets import QApplication
# 创建Qt应用程序
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
# 创建世界实例
world = MyWorld()
# 创建VR控制面板
print("创建VR控制面板...")
control_panel = VRControlPanel(world)
# 测试面板功能
print("✓ VR控制面板创建成功")
print(" - 面板标题:", control_panel.windowTitle())
print(" - 面板大小:", control_panel.size().width(), "x", control_panel.size().height())
# 显示面板(非阻塞)
control_panel.show()
print("✓ VR控制面板已显示")
print("\n💡 GUI控制面板功能:")
print(" - VR系统开关控制")
print(" - ALVR串流控制")
print(" - 实时状态监控")
print(" - 质量设置调整")
print(" - 控制器状态显示")
print(" - 性能监控")
# 短暂显示然后关闭
import time
time.sleep(2)
control_panel.close()
print("\n✓ VR控制面板测试完成")
except Exception as e:
print(f"✗ VR控制面板测试失败: {str(e)}")
return False
return True
def test_vr_interaction():
"""测试VR交互功能"""
print("=== VR交互功能测试 ===")
# 创建世界实例
world = MyWorld()
# 初始化VR系统
print("初始化VR系统...")
if not world.initializeVR():
print("✗ VR系统初始化失败")
return False
# 测试VR输入处理
print("\n🎮 测试VR输入处理:")
input_success = world.startVRInput()
if input_success:
print(" ✓ VR输入处理启动成功")
# 测试控制器射线显示
print("\n🌟 测试控制器射线:")
ray_success = world.showControllerRays(True)
if ray_success:
print(" ✓ 控制器射线显示启用")
else:
print(" ⚠ 控制器射线显示失败")
# 测试手势识别
print("\n✋ 测试手势识别:")
gesture_success = world.setVRGestureEnabled(True)
if gesture_success:
print(" ✓ VR手势识别启用")
else:
print(" ⚠ VR手势识别启用失败")
# 测试VR交互
print("\n🤏 测试VR交互:")
interaction_success = world.setVRInteractionEnabled(True)
if interaction_success:
print(" ✓ VR交互功能启用")
else:
print(" ⚠ VR交互功能启用失败")
# 获取控制器状态
print("\n🎮 控制器状态:")
controllers = world.getAllControllers()
for i, controller in enumerate(controllers):
if controller:
print(f" 控制器 {i}: 可用")
state = world.getControllerState(i)
if state:
print(f" - 位置: {state.get('position', 'N/A')}")
print(f" - 旋转: {state.get('rotation', 'N/A')}")
print(f" - 按钮: {state.get('buttons', 'N/A')}")
else:
print(f" 控制器 {i}: 不可用")
# 停止VR输入
world.stopVRInput()
print("\n✓ VR输入处理已停止")
else:
print(" ⚠ VR输入处理启动失败")
# 关闭VR系统
world.shutdownVR()
print("\n✓ VR系统已关闭")
return True
def run_all_tests():
"""运行所有测试"""
print("=== 运行所有VR测试 ===")
tests = [
("基本VR功能", test_basic_vr_functionality),
("VR模拟模式", test_simulation_mode),
("ALVR串流", test_alvr_streaming),
("VR GUI控制面板", test_vr_gui_control_panel),
("VR交互功能", test_vr_interaction)
]
results = []
for test_name, test_func in tests:
print(f"\n{'='*50}")
print(f"正在运行: {test_name}")
print('='*50)
try:
success = test_func()
results.append((test_name, success))
if success:
print(f"{test_name} 测试通过")
else:
print(f"{test_name} 测试失败")
except Exception as e:
print(f"{test_name} 测试出错: {str(e)}")
results.append((test_name, False))
# 打印总结
print(f"\n{'='*50}")
print("测试总结")
print('='*50)
passed = sum(1 for _, success in results if success)
total = len(results)
for test_name, success in results:
status = "✓ 通过" if success else "✗ 失败"
print(f"{test_name}: {status}")
print(f"\n总计: {passed}/{total} 个测试通过")
if passed == total:
print("🎉 所有测试都通过了!")
else:
print("⚠ 部分测试失败,请检查上述输出")
return passed == total
def print_vr_requirements():
"""打印VR系统要求"""
print("📋 VR系统要求说明")
print("="*50)
print("🔧 软件要求:")
print(" - Python 3.8+")
print(" - Panda3D")
print(" - PyQt5")
print(" - OpenVR库 (pip install openvr)")
print(" - 其他依赖见 requirements/vr-requirements.txt")
print("\n🎮 硬件要求完整VR模式:")
print(" - 支持VR的显卡 (GTX 1060/RX 580 或更好)")
print(" - VR头盔 (Quest 2/3, Valve Index, HTC Vive等)")
print(" - 足够的USB端口或无线连接")
print("\n🌐 连接方式:")
print(" 有线连接:")
print(" - Valve Index: DisplayPort + USB 3.0")
print(" - HTC Vive: HDMI + USB 3.0")
print(" - Quest 2/3: USB-C (Quest Link)")
print(" 无线连接:")
print(" - Quest 2/3: 通过ALVR串流")
print(" - 需要5GHz Wi-Fi网络")
print(" - 需要ALVR服务器运行")
print("\n🔄 启动顺序完整VR模式:")
print(" 1. 确保VR头盔已连接并识别")
print(" 2. 启动SteamVR")
print(" 3. (可选) 启动ALVR服务器Quest无线")
print(" 4. 运行VR测试脚本")
print("\n🎮 模拟模式说明:")
print(" - 无需VR硬件")
print(" - 模拟头盔和控制器追踪")
print(" - 立体渲染到窗口")
print(" - 适用于开发和调试")
print("\n💡 故障排除:")
print(" - 如果OpenVR初始化失败系统会自动切换到模拟模式")
print(" - 检查SteamVR是否正在运行")
print(" - 确认VR头盔被系统识别")
print(" - 检查USB/DisplayPort连接")
print(" - 重启SteamVR和头盔")
def main():
"""主函数"""
print("🎮 VR功能测试脚本")
print("="*50)
# 显示要求说明
print_vr_requirements()
print("\n请选择测试类型:")
print("1. 基本VR功能测试")
print("2. VR模拟模式测试")
print("3. ALVR串流测试")
print("4. VR GUI控制面板")
print("5. VR交互功能测试")
print("6. 运行所有测试")
print("7. 查看VR系统要求")
try:
choice = input("请输入选择 (1-7): ")
if choice == "1":
success = test_basic_vr_functionality()
elif choice == "2":
success = test_simulation_mode()
elif choice == "3":
success = test_alvr_streaming()
elif choice == "4":
success = test_vr_gui_control_panel()
elif choice == "5":
success = test_vr_interaction()
elif choice == "6":
success = run_all_tests()
elif choice == "7":
print_vr_requirements()
return
else:
print("无效的选择")
return
print("\n" + "="*50)
if success:
print("✓ 测试成功")
else:
print("✗ 测试失败")
except KeyboardInterrupt:
print("\n用户中断测试")
except Exception as e:
print(f"测试过程中发生错误: {str(e)}")
if __name__ == "__main__":
main()