04. 헬로 플로어
첫 번째 촉각 효과: 커서가 그 위로 눌려 들어갈 때 반작용력을 발생시키는 가상의 수평지면입니다. 이 힘은 간단한 페널티 스프링 모델로, —stiffness × penetration_depth——통과 set_cursor_force Z축을 따라 가해진다.
다음 내용을 배우게 됩니다:
- 사용
set_cursor_force처벌용 스프링 힘을 가하다 - 읽기
cursor_position그리고 힘을 실시간으로 계산하며 - (파이썬) 설정 작업 공간 사전 설정(
arm_front_centered), 원점을 작업 공간의 중심에 위치시킨다 - (파이썬)을 통해
keyboard지면의 높이와 강성을 상호작용 방식으로 조절한다
업무 흐름
- 열기
ws://localhost:10001WebSocket을 열고 첫 번째 상태 프레임을 기다립니다. - 첫 번째 프레임에서: 등록 세션 프로필. Python 버전은 또한 다음을 전송합니다.
configure.preset: arm_front_centered, 원점을 작업 공간의 중앙에 위치시킵니다. C++ 버전은 기기에서 현재 활성화된 구성을 사용합니다. - 각 프레임: 읽기
cursor_position.z, 계산force_z = max(0, (floor_pos - z) * stiffness), 그리고 이를 통해set_cursor_force명령을 다시 전송합니다. - 이후의 각 주기에서는 힘 명령만 전송되며, 세션 프로파일은 일회성 핸드셰이크에 불과합니다.
- (Python) 매 주기마다 키보드의 방향키를 폴링하여 실시간으로 업데이트합니다.
floor_pos/stiffness。
매개변수
| 명칭 | 기본값 | 용도 |
|---|---|---|
floor_pos | 0.10 m | 가상 지면 평면의 Z 좌표 |
stiffness | 1000 해당 없음 | 탄성 계수 (1 mm 관통 시 → 1 N) |
PRINT_EVERY_MS | 100–200 | 원격 측정 유량 조절 |
| 세션 프로필 이름 | co.haply.inverse.tutorials:hello-floor | Haply Hub에서 이 시뮬레이션을 식별합니다. |
파이썬 버전 사용 keyboard 패키지 (Linux에서는 권한 상승이 필요함):
↑/↓——지면 높이기 / 낮추기←/→——강성 감소 / 증가R——기본값으로 복원
서비스 주기 동안 힘은합산될 수 있습니다. 즉, 장치로 전송되기 전에 각 출처의 힘이 먼저 합산됩니다. 이 튜토리얼과 같은 예제는 다른 힘 생성 소스와 공존할 수 있으며, 서로를 방해하지 않습니다.
읽은 상태 필드
출처: data.inverse3[i].state:
cursor_position.z—vec3, 관통 깊이를 계산하는 데 사용됨current_cursor_force— 원격 측정 데이터 전송용
보내기 / 받기
각 주기마다: 커서의 Z 좌표를 읽어들이고, 계산한다 force_z = max(0, (floor_pos - z) * stiffness),그리고 다음 메시지를 보내세요 set_cursor_force 명령어. 제1조에 따라 전송되는 메시지에는 세션 구성 파일(모든 버전)이 포함되며, Python 버전의 경우 다음도 함께 포함됩니다. configure.preset: arm_front_centered。
- 파이썬
- C++ (nlohmann)
- C++ (Glaze)
단일 비동기 루프. 첫 번째 프레임의 핸드셰이크에는 프로필과 configure.preset, ~하게 하여 floor_pos = 0.1 작업 공간의 중심 좌표와 정렬합니다.
async with websockets.connect(URI) as websocket:
while True:
msg = await websocket.recv()
data = json.loads(msg)
if first_message:
first_message = False
device_id = data["inverse3"][0]["device_id"]
# Handshake: profile + preset (one-shot)
request_msg = {
"session": {"configure": {"profile": {"name": "co.haply.inverse.tutorials:hello-floor"}}},
"inverse3": [{
"device_id": device_id,
"configure": {"preset": {"preset": "arm_front_centered"}}
}]
}
else:
# Per tick: compute force along Z, send set_cursor_force
z = data["inverse3"][0]["state"]["cursor_position"]["z"]
force_z = 0.0 if z > floor_pos else (floor_pos - z) * stiffness
request_msg = {
"inverse3": [{
"device_id": device_id,
"commands": {"set_cursor_force":
{"vector": {"x": 0.0, "y": 0.0, "z": force_z}}}
}]
}
await websocket.send(json.dumps(request_msg))
libhv 콜백 모델——onmessage는 WebSocket I/O 스레드에서 실행되며, 메인 스레드는 ENTER 키를 기다리며 차단됩니다. C++ 버전은 가장 기본적인 핸드셰이크 절차만 제공합니다(세션 프로파일만 포함되며, 사전 설정은 포함되지 않음).
ws.onmessage = [&](const std::string &msg) {
const json data = json::parse(msg);
// If no Inverse3 yet, ask the service to re-send the full state
if (!data.contains("inverse3") || data["inverse3"].empty()) {
ws.send(R"({"session":{"force_render_full_state":{}}})");
return;
}
json request = {};
if (first_message) {
first_message = false;
request["session"] = {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:hello-floor"}}}}}};
}
request["inverse3"] = json::array();
for (auto &el : data["inverse3"].items()) {
const float z = el.value()["state"]["cursor_position"]["z"].get<float>();
const float force_z = z > floor_pos ? 0.0f : (floor_pos - z) * stiffness;
request["inverse3"].push_back({
{"device_id", el.value()["device_id"]},
{"commands", {{"set_cursor_force",
{{"vector", {{"x", 0.0}, {"y", 0.0}, {"z", force_z}}}}}}},
});
}
ws.send(request.dump());
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
libhv 콜백 모델과 동일하며, 본문 부분만 다릅니다. 상태와 명령 모두 강타입 구조체를 사용합니다.std::optional<session_cmd> 일회용 구성 파일 저장 — 이 옵션이 설정되지 않은 경우, Glaze는 직렬화된 JSON에서 이를 생략합니다.
// Struct models
struct vec3 { float x{}, y{}, z{}; };
struct inverse_state { vec3 cursor_position{}, current_cursor_force{}; };
struct inverse_device { std::string device_id; inverse_state state; };
struct devices_message { std::vector<inverse_device> inverse3; };
struct set_cursor_force_cmd { vec3 vector; };
struct commands_message {
std::optional<session_cmd> session;
std::vector<device_commands> inverse3;
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
if (data.inverse3.empty()) {
ws.send(R"({"session":{"force_render_full_state":{}}})");
return;
}
commands_message out_cmds{};
if (first_message) {
first_message = false;
out_cmds.session = session_cmd{ /* profile = hello-floor */ };
}
for (const auto &dev : data.inverse3) {
const float z = dev.state.cursor_position.z;
const float force_z = z > floor_pos ? 0.0f : (floor_pos - z) * stiffness;
device_commands dc{ .device_id = dev.device_id };
dc.commands.set_cursor_force = set_cursor_force_cmd{{0.0f, 0.0f, force_z}};
out_cmds.inverse3.push_back(std::move(dc));
}
std::string out_json;
(void)glz::write_json(out_cmds, out_json);
ws.send(out_json);
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
튜토리얼 04는 SDK와 함께 로컬에 설치됩니다. 서비스 설치 디렉터리 내의 tutorials/04-haply-inverse-hello-floor/ 에서 검색하세요.
소스 코드: Python · C++ · C++ Glaze
관련 내용: 제어 명령(set_cursor_force) · 마운트 및 작업 공간 (기본 설정) · 형식 (vec3) · 대화 · 튜토리얼 07 (베이스와 장착)