04. 헬로 플로어
첫 번째 햅틱 효과는 가상의 수평 바닥입니다. 커서가 바닥을 누르면 바닥에서 반작용하는 힘이 발생하여 밀어냅니다. 이 힘은 stiffness × penetration_depth을 기준으로 하는 단순한 페널티 스프링이며, set_cursor_force을 통해 Z축을 따라 적용됩니다.
학습 내용:
set_cursor_force를 사용하여 페널티 스프링 힘 적용하기cursor_position을 읽고 실시간으로 힘을 계산하기- (Python) 원점이 작업 공간의 중앙에 오도록 작업 공간 사전 설정(
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명령에 따라 다시 전송합니다. - 이후 틱에서는 힘 명령만 전송합니다. 세션 프로필은 일회성 핸드셰이크입니다.
- (파이썬) 매 틱마다 키보드의 방향키를 폴링하여
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 허브에서 이 시뮬레이션을 식별 |
파이썬의 변형은 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를 전송합니다. 첫 번째 전송 메시지에는 (모든 변형에서) 세션 프로필이 포함되며, 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/에서 확인하실 수 있습니다.
관련 문서: 제어 명령 (set_cursor_force) · 마운트 및 작업 공간 (사전 설정) · 타입 (vec3) · 세션 · 튜토리얼 07 (베이스 및 마운트)