04. 바닥아, 안녕
첫 번째 햅틱 효과: 커서가 바닥에 닿으면 밀어내는 가상 수평 바닥입니다. 이 힘은 단순한 페널티 스프링 효과입니다 — stiffness × penetration_depth — Z 방식의 아플리케 via set_cursor_force.
이 강좌에서 배우게 될 내용:
- 사용하기
set_cursor_force벌칙 스프링 힘을 적용하기 위해 - 읽기
cursor_position그리고 실시간으로 힘을 계산하고 - (파이썬) 정의하기 작업 공간 사전 설정 (
arm_front_centered) 원점이 작업 공간의 중심에 오도록 하기 위해 - (Python) 패키지를 사용하여 키보드로 바닥 높이와 강성을 대화형으로 조정하기
keyboard
진행 과정
- 다음으로 WebSocket 연결을 설정하십시오.
ws://localhost:10001그리고 첫 번째 상태 프레임까지 기다리세요. - 첫 번째 프레임에서: 다음을 기록하십시오. 세션 프로필. 또한 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생중계.
매개변수
| Nom | 기본값 | 역할 |
|---|---|---|
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에서 이 시뮬레이션을 식별하세요. |
Python 버전은 다음 패키지를 사용합니다. keyboard (리눅스에서는 높은 권한이 필요합니다) :
↑/↓— 바닥면을 올리거나 내리기←/→— 강성을 낮추다 / 높이다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 (기본 및 편집)