# 두 관절 역운동학 (Two-bone IK)

램프 머리가 닿을 곳을 정하면 받침과 팔꿈치가 함께 회전해 머리를 그곳에 맞춥니다.

## 체험 방법

‘가까이 당기기’와 ‘책 위로’를 번갈아 눌러 팔꿈치 각도를 보세요. ‘작업대 끝으로’를 누르면 램프와 표적 사이에 점선이 나타납니다.

## 재현 기준

두 마디의 길이는 각각 도면 기준 86과 98입니다. 목표까지의 거리가 184를 넘으면 팔꿈치가 180도로 펴집니다. 방향키는 표적을 8단위씩 옮깁니다.

## 기기별 조작

- PC · 작업대에서 드래그하거나 Tab으로 그림에 초점을 둔 뒤 방향키로 표적을 옮기세요.
- iOS · 작업대를 탭하거나 표적을 끌어 램프를 접고 펴 보세요. ‘작업대 끝으로’를 눌러 도달 한계를 확인하세요.
- Android · 작업대를 탭하거나 표적을 끌어 램프를 접고 펴 보세요. ‘작업대 끝으로’를 눌러 도달 한계를 확인하세요.

## 적용할 때

캐릭터가 손을 뻗거나 관절식 조명이 책을 비출 때처럼 끝점에서 거꾸로 관절의 자세를 정할 때 씁니다.

## 그대로 보낼 요청

> 두 마디의 길이와 받침 위치를 고정하고, 램프 머리의 표적을 옮길 때 두 관절이 함께 회전하게 해 주세요. 닿지 않는 표적은 램프가 최대로 뻗은 곳과 점선으로 이어 주세요.

## 참고한 동작

[Godot · TwoBoneIK](https://docs.godotengine.org/en/stable/classes/class_skeletonmodification2dtwoboneik.html)

## 독립 실행 코드

아래 전체 코드를 HTML로 저장해 브라우저에서 엽니다.

```html
<!doctype html>
<html lang="ko" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>제본 작업등 · 두 관절 역운동학</title>
<style>
* { box-sizing: border-box; }
:root { color-scheme: light; font: 15px/1.5 system-ui, sans-serif; background: #f3efe7; color: #292632; }
body { margin: 0; }
main { max-width: 720px; margin: auto; padding: clamp(12px, 3.5vw, 26px); }
header, .readout, .presets { display: flex; align-items: baseline; flex-wrap: wrap; gap: 5px 12px; }
header { justify-content: space-between; margin-bottom: 12px; }
h1 { margin: 0; font-size: clamp(21px, 4.6vw, 30px); line-height: 1.15; letter-spacing: -.04em; }
header small { color: #635e63; font-size: .83rem; }
.workbench { background: #242130; border-radius: 16px; overflow: hidden; }
#stage { display: block; width: 100%; touch-action: none; cursor: grab; }
#stage:active { cursor: grabbing; }
:focus-visible { outline: 3px solid #14695e; outline-offset: 3px; }
#stage:focus-visible { outline: 3px solid #a7e8d4; outline-offset: -5px; }
.readout { padding: 10px 15px; border-top: 1px solid #514855; color: #f2e8df; align-items: center; gap: 8px 13px; }
#status { flex: 1; font-size: .87rem; }
#status::before { content: ''; display: inline-block; width: 9px; height: 9px; margin-inline-end: 8px; border-radius: 50%; background: #92d6bc; }
#status[data-limit="true"]::before { border-radius: 1px; background: #ffb56f; transform: rotate(45deg); }
.angles { color: #f3dac0; font: 12px/1.4 ui-monospace, monospace; }
.angles span { white-space: nowrap; }
.presets { margin: 13px 0 6px; gap: 6px; }
button { font-family: inherit; font-size: .86rem; font-weight: 600; line-height: 1.2; min-height: 42px; cursor: pointer; padding: 6px 13px; border-radius: 24px; border: 1px solid #c6bfb7; background: #faf7f0; color: #332d35; }
button[aria-pressed="true"] { color: white; border-color: #53424f; background: #53424f; }
button:hover { border-color: #53424f; }
.hint { margin: 8px 0 0; color: #625b60; font-size: .86rem; }
@media (pointer:coarse) { button { min-height: 44px; } }
@media (max-width:350px) { main { padding: 9px; } .readout { padding: 8px 10px; } }
</style>
</head>
<body>
<main>
  <header><h1 data-copy="title">제본 작업등</h1><small data-copy="technique">두 관절 역운동학</small></header>
  <section class="workbench" aria-labelledby="bench-title">
    <svg id="stage" viewBox="0 0 440 228" role="img" tabindex="0" aria-labelledby="bench-title" aria-describedby="hint">
      <title id="bench-title" data-copy="drawing">제본 작업대와 두 마디로 접히는 램프</title>
      <defs>
        <linearGradient id="wall" x2="1" y2="1" gradientUnits="objectBoundingBox"><stop stop-color="#343041"/><stop offset="1" stop-color="#201e2d"/></linearGradient>
        <linearGradient id="glow" x1="0" y1="0" x2="0" y2="1" gradientUnits="objectBoundingBox"><stop stop-color="#ffdb98" stop-opacity=".56"/><stop offset="1" stop-color="#f7b873" stop-opacity=".045"/></linearGradient>
        <pattern id="grid" patternUnits="userSpaceOnUse" width="16" height="16"><circle cx="2" cy="2" r=".75" fill="#c2b4c6" opacity=".22"/></pattern>
      </defs>
      <rect width="440" height="228" fill="url(#wall)"/>
      <rect width="440" height="199" fill="url(#grid)"/>
      <path d="M0 199 H440 V228 H0Z" fill="#745965"/>
      <path d="M0 212 H440 V228 H0Z" fill="#453643"/>
      <path d="M0 200 H440" stroke="#a7898b"/>
      <ellipse cx="105" cy="202" rx="43" ry="5" fill="#41303d" opacity=".7"/>
      <path d="M68 197 Q69 191 77 190 L96 188 V179 H112 V188 L133 190 Q140 191 141 197 L136 201 H70Z" fill="#b5906f" stroke="#2a2431" stroke-width="2.4"/>
      <path d="M75 194 L134 194" stroke="#f7d8a8" stroke-width="2"/>
      <!-- A bound notebook and loose pages show where the light lands. -->
      <g stroke-linejoin="round">
        <path d="M202 198 L238 177 Q253 174 268 181 Q282 173 300 175 L338 192 L302 202 Q286 199 273 204 Q254 202 241 205Z" fill="#a66772" stroke="#332935" stroke-width="2"/>
        <path d="M205 195 L238 174 Q251 172 267 178 Q282 169 299 172 L333 189 L302 198 Q286 196 272 201 Q254 197 240 201Z" fill="#ecdbbd"/>
        <path d="M267 178 Q265 185 272 201 M228 189 Q245 181 258 185 M279 179 Q289 176 301 181 M285 184 Q296 181 309 187" fill="none" stroke="#ac9488" stroke-width="1.6"/>
      </g>
      <path id="beam" fill="url(#glow)"/>
      <line id="arm-under" stroke="#201d2b" stroke-width="13" stroke-linecap="round"/>
      <line id="arm-over" stroke="#ddae75" stroke-width="8" stroke-linecap="round"/>
      <line id="fore-under" stroke="#211b28" stroke-width="12" stroke-linecap="round"/>
      <line id="fore-over" stroke="#edd0a8" stroke-width="7" stroke-linecap="round"/>
      <circle cx="104" cy="179" r="9" fill="#79616b" stroke="#f2d4a7" stroke-width="3"/>
      <g id="elbow"><circle r="9" fill="#372d3d" stroke="#deb681" stroke-width="3.5"/><circle r="3" fill="#f1d4ae"/></g>
      <g id="head"><path d="M-5 -1 Q-6 -7 2 -8 Q7 -8 9 -3 L19 3 L8 18 L-5 9Z" fill="#d78f73" stroke="#2e2630" stroke-width="2.4"/><path d="M7 18 L19 3 Q23 5 20 9 L12 19 Q10 21 7 18" fill="#ffe0a0"/><circle r="3" fill="#493345"/></g>
      <line id="gap" stroke="#ffbd7e" stroke-width="1.5" stroke-dasharray="3 4"/>
      <g id="target" fill="none" stroke="#a4f0d3" stroke-width="1.8"><circle r="13" stroke-dasharray="4 3"/><path d="M-19 0 H-13 M13 0 H19 M0 -19 V-13 M0 13 V19"/></g>
    </svg>
    <div class="readout"><span id="status" role="status"></span><div class="angles"><span><span data-copy="base">받침</span> <b id="base-angle"></b></span> · <span><span data-copy="elbow">팔꿈치</span> <b id="elbow-angle"></b></span></div></div>
  </section>
  <div class="presets" role="group" id="presets">
    <button type="button" data-preset="near" data-copy="near">가까이 당기기</button>
    <button type="button" data-preset="book" data-copy="book">책 위로</button>
    <button type="button" data-preset="far" data-copy="far">작업대 끝으로</button>
  </div>
  <p class="hint" id="hint" data-copy="hint">표적을 드래그하거나 작업대를 누르세요. 키보드로는 작업대에 초점을 두고 방향키를 누르세요.</p>
</main>
<script>
'use strict';
const messages = {
  ko: {title:'제본 작업등', technique:'두 관절 역운동학', drawing:'제본 작업대와 두 마디로 접히는 램프', base:'받침', elbow:'팔꿈치', near:'가까이 당기기', book:'책 위로', far:'작업대 끝으로', positions:'표적 위치', reached:'표적에 닿음', limited:'최대 길이에 도달', hint:'표적을 드래그하거나 작업대를 누르세요. 키보드로는 작업대에 초점을 두고 방향키를 누르세요.'},
  en: {title:'Bookbinder’s lamp', technique:'Two-bone IK', drawing:'A bookbinding bench with a two-link desk lamp', base:'Base', elbow:'Elbow', near:'Pull closer', book:'Over the book', far:'Far edge', positions:'Target position', reached:'Target reached', limited:'At full extension', hint:'Drag the target or tap the bench. To use the arrow keys, focus the drawing first.'},
  es: {title:'Lámpara de encuadernación', technique:'Cinemática inversa de dos huesos', drawing:'Una mesa de encuadernación con una lámpara de dos segmentos', base:'Base', elbow:'Codo', near:'Acercar', book:'Sobre el libro', far:'Borde lejano', positions:'Posición del objetivo', reached:'Objetivo alcanzado', limited:'Extensión máxima', hint:'Arrastra el objetivo o toca la mesa. Para usar las flechas, enfoca primero el dibujo.'},
  'zh-Hans': {title:'装帧工作灯', technique:'双骨骼反向运动学', drawing:'装帧台上的双连杆台灯', base:'底座', elbow:'肘部', near:'拉近', book:'移到书上方', far:'移到桌边', positions:'目标位置', reached:'已到达目标', limited:'已完全伸展', hint:'拖动目标或轻点工作台。用键盘操作时，先将焦点移到图中，再按方向键。'}
};
const params = new URLSearchParams(location.search);
const requested = (params.get('lang') || document.documentElement.lang || 'ko').toLowerCase();
const language = requested.startsWith('zh') ? 'zh-Hans' : requested.split('-')[0];
const copy = messages[language] || messages.ko;
document.documentElement.lang = messages[language] ? language : 'ko';
document.title = copy.title + ' · ' + copy.technique;
for (const node of document.querySelectorAll('[data-copy]')) node.textContent = copy[node.dataset.copy];
document.querySelector('#presets').setAttribute('aria-label', copy.positions);

const stage = document.querySelector('#stage');
const base = {x: 104, y: 179};
const lengths = [86, 98];
const presets = {near:{x:155, y:122}, book:{x:248, y:103}, far:{x:369, y:90}};
const controls = [...document.querySelectorAll('[data-preset]')];
const status = document.querySelector('#status');
const get = id => document.getElementById(id);
const links = [[get('arm-under'), get('arm-over')], [get('fore-under'), get('fore-over')]];
const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
const degrees = angle => Math.round(angle * 180 / Math.PI) + '°';
let target = {...presets.book};
let animation = 0;
let pointer = null;
function armBetween(lines, start, end) {
  for (const line of lines) {
    line.setAttribute('x1', start.x); line.setAttribute('y1', start.y);
    line.setAttribute('x2', end.x); line.setAttribute('y2', end.y);
  }
}
function render(point) {
  target = point;
  const dx = point.x - base.x, dy = point.y - base.y;
  const distance = Math.hypot(dx, dy);
  const [upper, lower] = lengths;
  const reach = clamp(distance, Math.abs(upper - lower), upper + lower);
  const ux = dx / distance, uy = dy / distance;
  const tip = {x: base.x + ux * reach, y: base.y + uy * reach};
  // Intersect two circles; choose the joint above the shoulder-to-tip line.
  const along = (upper * upper - lower * lower + reach * reach) / (2 * reach);
  const rise = Math.sqrt(Math.max(0, upper * upper - along * along));
  const joint = {x: base.x + ux * along + uy * rise, y: base.y + uy * along - ux * rise};
  armBetween(links[0], base, joint);
  armBetween(links[1], joint, tip);
  get('elbow').setAttribute('transform', 'translate(' + joint.x + ' ' + joint.y + ')');
  get('head').setAttribute('transform', 'translate(' + tip.x + ' ' + tip.y + ')');
  get('beam').setAttribute('d', 'M' + (tip.x + 18) + ' ' + (tip.y + 5) + ' L' + (tip.x + 103) + ' 200 H' + (tip.x - 12) + ' L' + (tip.x + 9) + ' ' + (tip.y + 18) + 'Z');
  armBetween([get('gap')], tip, point);
  get('target').setAttribute('transform', 'translate(' + point.x + ' ' + point.y + ')');
  const limited = distance > upper + lower + .001;
  get('target').setAttribute('stroke', limited ? '#ffbd7e' : '#a4f0d3');
  status.dataset.limit = String(limited);
  const nextMessage = limited ? copy.limited : copy.reached;
  if (status.textContent !== nextMessage) status.textContent = nextMessage;
  get('base-angle').textContent = degrees(Math.atan2(base.y - joint.y, joint.x - base.x));
  get('elbow-angle').textContent = degrees(Math.acos(clamp((upper * upper + lower * lower - reach * reach) / (2 * upper * lower), -1, 1)));
  for (const control of controls) {
    const preset = presets[control.dataset.preset];
    control.setAttribute('aria-pressed', String(Math.abs(preset.x - point.x) < .01 && Math.abs(preset.y - point.y) < .01));
  }
}
function moveFree(x, y) {
  cancelAnimationFrame(animation);
  render({x:clamp(x, 123, 412), y:clamp(y, 32, 173)});
}
function choosePreset(event) {
  cancelAnimationFrame(animation);
  const end = presets[event.currentTarget.dataset.preset];
  if (matchMedia('(prefers-reduced-motion: reduce)').matches || document.documentElement.matches('.motion-reduced,.reduced-motion') || document.body.matches('.motion-reduced,.reduced-motion')) { render({...end}); return; }
  const start = {...target}, startTime = performance.now();
  function animate(now) {
    const progress = clamp((now - startTime) / 360, 0, 1);
    const eased = progress * progress * (3 - 2 * progress);
    render({x:start.x + (end.x - start.x) * eased, y:start.y + (end.y - start.y) * eased});
    if (progress < 1) animation = requestAnimationFrame(animate);
  }
  animation = requestAnimationFrame(animate);
}
for (const control of controls) control.addEventListener('click', choosePreset);
function positionFromEvent(event) {
  const point = stage.createSVGPoint();
  point.x = event.clientX; point.y = event.clientY;
  const local = point.matrixTransform(stage.getScreenCTM().inverse());
  moveFree(local.x, local.y);
}
stage.addEventListener('pointerdown', event => {
  if (pointer !== null || event.button !== 0) return;
  pointer = event.pointerId; stage.setPointerCapture(pointer);
  positionFromEvent(event);
});
stage.addEventListener('pointermove', event => { if (event.pointerId === pointer) positionFromEvent(event); });
stage.addEventListener('lostpointercapture', event => { if (event.pointerId === pointer) pointer = null; });
const arrows = {ArrowLeft:[-8,0], ArrowRight:[8,0], ArrowUp:[0,-8], ArrowDown:[0,8]};
stage.addEventListener('keydown', event => {
  const delta = arrows[event.key];
  if (!delta) return;
  event.preventDefault();
  moveFree(target.x + delta[0], target.y + delta[1]);
});
render(target);
</script>
</body></html>
```

