Files
homeclaw/web-ui/html/k2-app.html
T
kimandClaude Code 8fbf581ca1 feat: k2-app Cura 스타일 3D 슬라이싱 GUI (Three.js 툴패스 레이어뷰)
폼 기반 프로필 에디터를 CuraEngine GUI처럼 풀뷰포트 3D 뷰로 교체.
Three.js r128 UMD 벤더(/vendor/three/)로 260³ 빌드 플레이트 위 STL을
3D로 띄우고, 슬라이스 후 gcode를 파싱해 ;TYPE:별 툴패스를 레이어별로 시각화.
슬라이스↔업로드 흐름을 Cura식으로 분리(slice≠전송) — 슬라이스만 하고
툴패스 검토 뒤 명시적으로 업로드/출력 시작.

- web-ui/js/k2/slicer-view.js: 3D 씬 + STL 로드 + gcode 툴패스 파서 + 레이어 슬라이더
  + 프로파일 패널(스키마·오버라이드·저장) 이전. ;LAYER_CHANGE 마커로 레이어 경계
  감지(Z변화 감지는 start_gcode 프라이밍 Z3→Z0.2→Z1이 가짜 층을 만드는 걸 회피).
- routes-k2.ts: /api/k2/slice 를 upload=0 기본(슬라이스만)으로 변경,
  POST /api/k2/upload·GET /api/k2/gcode/:filename 신규.
  gcode 라우트의 res.sendFile에 {dotfiles:'allow'} 추가 — 워크스페이스가
  .smallclaw(도트파일 디렉토리) 아래라 send 라이브러리 기본값 'ignore'가
  404 "Not Found"로 씹어버리는 걸 해결.
- k2-slicer-core.ts: parsePrusaFilament(mm/cm3) 추가.
- k2-app.html: 슬라이싱 모달→#slicer-overlay 컨테이너로 교체, Three.js 스크립트 로드.
  CAD 모달·카메라·Fluidd iframe은 그대로 유지.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-20 21:08:23 +09:00

335 lines
18 KiB
HTML
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.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🖨️ K2 콤보</title>
<link rel="icon" type="image/png" sizes="64x64" href="/homeclaw_logo.png">
<link rel="stylesheet" href="../css/styles.css">
<script>try{var _t=localStorage.getItem('homeclaw_theme')||'dark';document.documentElement.setAttribute('data-theme',_t);}catch(e){}</script>
<style>
:root{--brand:#f97316;}
html,body{height:100%;margin:0;padding:0;}
body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;display:flex;flex-direction:column;overflow:hidden;height:100dvh;}
.hdr{display:flex;align-items:center;gap:8px;padding:6px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex-shrink:0;}
.hdr h1{font-size:13px;font-weight:700;margin:0;}
.hdr-sp{flex:1;}
.hdr-btn{background:none;border:1.5px solid var(--line);border-radius:6px;padding:3px 9px;font-size:11px;color:var(--muted);cursor:pointer;font-family:inherit;transition:.15s;text-decoration:none;display:inline-flex;align-items:center;}
.hdr-btn:hover{border-color:var(--brand);color:var(--brand);}
.body-wrap{flex:1;min-height:0;display:flex;flex-direction:column;}
.cam-bar{flex-shrink:0;background:#000;display:flex;justify-content:center;position:relative;max-height:32vh;}
.cam-bar video{max-width:100%;max-height:32vh;display:block;background:#000;}
.cam-status{position:absolute;top:6px;right:10px;font-size:11px;color:#9ca3af;background:rgba(0,0,0,.5);padding:2px 8px;border-radius:6px;}
.cam-empty{color:var(--muted);font-size:12px;padding:16px;text-align:center;}
.frame-wrap{flex:1;min-height:0;position:relative;}
.frame-wrap iframe{width:100%;height:100%;border:none;display:block;}
.err{display:none;position:absolute;inset:0;align-items:center;justify-content:center;flex-direction:column;gap:10px;background:var(--bg);color:var(--muted);font-size:13px;text-align:center;padding:20px;}
.err.show{display:flex;}
.err a{color:var(--brand);}
/* ── 슬라이싱/CAD 공통 모달 클래스 ── */
.slice-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:50;align-items:center;justify-content:center;padding:16px;}
.slice-overlay.show{display:flex;}
.slice-modal{width:100%;max-width:520px;max-height:92vh;overflow-y:auto;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:16px;}
.slice-modal h2{font-size:14px;margin:0 0 12px;}
.slice-field{margin-bottom:10px;}
.slice-field label{display:block;font-size:11px;color:var(--muted);margin-bottom:3px;}
.slice-field input[type=file],.slice-field input[type=number],.slice-field input[type=text],.slice-field select{width:100%;box-sizing:border-box;background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:6px 8px;font-size:12px;color:var(--text);font-family:inherit;outline:none;}
.slice-field input:focus,.slice-field select:focus{border-color:var(--brand);}
.slice-row{display:flex;gap:8px;}
.slice-row .slice-field{flex:1;}
.slice-check{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text);margin-bottom:8px;}
.slice-btn{background:var(--brand);border:none;border-radius:8px;padding:9px 14px;font-size:13px;color:#fff;cursor:pointer;font-family:inherit;font-weight:700;}
.slice-btn:disabled{opacity:.5;cursor:not-allowed;}
.slice-close{float:right;background:none;border:none;font-size:16px;color:var(--muted);cursor:pointer;}
.slice-result{margin-top:12px;padding:10px;background:var(--panel-2);border-radius:8px;font-size:12px;line-height:1.7;display:none;}
.slice-result.show{display:block;}
.slice-err{margin-top:10px;color:#ef4444;font-size:12px;display:none;}
.slice-err.show{display:block;}
/* ── 3D 슬라이서(Cura 스타일) 풀뷰포트 오버레이 — 실제 스타일은 slicer-view.js가 주입 ── */
#slicer-overlay{display:none;position:fixed;inset:0;z-index:55;}
#slicer-overlay.show{display:block;}
/* ── CAD(STL 확인) 모달 ── */
.cad-modal{max-width:520px;}
.cad-field select{width:100%;box-sizing:border-box;background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:6px 8px;font-size:12px;color:var(--text);font-family:inherit;outline:none;}
.cad-view-btns{display:flex;gap:4px;flex-wrap:wrap;margin:8px 0;}
.cad-view-btn{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:4px 9px;font-size:11px;color:var(--muted);cursor:pointer;font-family:inherit;}
.cad-view-btn.active{border-color:var(--brand);color:var(--brand);}
.cad-preview{width:100%;aspect-ratio:1/1;background:#1a1a1a;border-radius:8px;display:flex;align-items:center;justify-content:center;overflow:hidden;margin-bottom:8px;}
.cad-preview img{width:100%;height:100%;object-fit:contain;}
.cad-preview .cad-placeholder{color:#666;font-size:11px;}
.cad-info{font-size:11px;color:var(--muted);margin-bottom:10px;line-height:1.7;}
.cad-hole-toggle{background:none;border:1px dashed var(--line);border-radius:6px;padding:5px 10px;font-size:11px;color:var(--muted);cursor:pointer;font-family:inherit;width:100%;text-align:left;margin-top:6px;}
.cad-hole-toggle:hover{border-color:var(--brand);color:var(--brand);}
.cad-hole-form{display:none;margin-top:8px;padding-top:8px;border-top:1px solid var(--line);}
.cad-hole-form.show{display:block;}
</style>
</head>
<body>
<header class="hdr">
<a href="/" style="text-decoration:none;font-size:13px;color:var(--muted)">← 홈</a>
<h1>🖨️ K2 콤보</h1>
<span class="hdr-sp"></span>
<button class="hdr-btn" onclick="openSlicer()">🔪 슬라이싱</button>
<button class="hdr-btn" onclick="openCadModal()">🔧 STL 확인</button>
<button class="hdr-btn" onclick="reconnectCam()">📷 카메라 재연결</button>
<button class="hdr-btn" onclick="reloadFrame()">↺ 새로고침</button>
<a class="hdr-btn" href="https://print.applecherry.net/" target="_blank">↗ 새 탭</a>
<button class="hdr-btn" onclick="toggleTheme()">🌙</button>
</header>
<div class="body-wrap">
<div class="cam-bar" id="cam-bar">
<video id="k2-cam" autoplay muted playsinline></video>
<span class="cam-status" id="cam-status">연결 중...</span>
</div>
<div class="frame-wrap">
<iframe id="k2-frame" src="https://print.applecherry.net/" title="Fluidd"></iframe>
<div class="err" id="k2-err">
<div>Fluidd를 불러오지 못했습니다 (print.applecherry.net).</div>
<div><a href="https://print.applecherry.net/" target="_blank">새 탭에서 직접 열기 ↗</a></div>
</div>
</div>
</div>
<div id="slicer-overlay"></div>
<div class="slice-overlay" id="cad-overlay">
<div class="slice-modal cad-modal">
<button class="slice-close" onclick="closeCadModal()">✕</button>
<h2>🔧 STL 확인</h2>
<div class="cad-field">
<label>파일</label>
<select id="cad-file-select" onchange="onCadFileChange()"></select>
</div>
<div class="cad-view-btns" id="cad-view-btns">
<button class="cad-view-btn active" data-view="iso" onclick="cadSetView('iso')">비스듬히</button>
<button class="cad-view-btn" data-view="top" onclick="cadSetView('top')">위</button>
<button class="cad-view-btn" data-view="bottom" onclick="cadSetView('bottom')">아래</button>
<button class="cad-view-btn" data-view="front" onclick="cadSetView('front')">앞</button>
<button class="cad-view-btn" data-view="back" onclick="cadSetView('back')">뒤</button>
<button class="cad-view-btn" data-view="left" onclick="cadSetView('left')">왼쪽</button>
<button class="cad-view-btn" data-view="right" onclick="cadSetView('right')">오른쪽</button>
</div>
<div class="cad-preview" id="cad-preview"><span class="cad-placeholder" id="cad-placeholder">파일을 선택하세요</span><img id="cad-preview-img" style="display:none"></div>
<div class="cad-info" id="cad-info"></div>
<button class="cad-hole-toggle" onclick="toggleHoleForm()">🕳️ 구멍 뚫기 ▾</button>
<div class="cad-hole-form" id="cad-hole-form">
<div class="slice-row">
<div class="slice-field"><label>X</label><input type="number" id="hole-x" value="0" step="0.1"></div>
<div class="slice-field"><label>Y</label><input type="number" id="hole-y" value="0" step="0.1"></div>
<div class="slice-field"><label>Z</label><input type="number" id="hole-z" value="0" step="0.1"></div>
</div>
<div class="slice-row">
<div class="slice-field"><label>지름(mm)</label><input type="number" id="hole-diameter" value="2" step="0.1" min="0.1"></div>
<div class="slice-field"><label>길이(mm)</label><input type="number" id="hole-depth" value="20" step="0.5"></div>
<div class="slice-field"><label>방향축</label>
<select id="hole-axis"><option value="z">Z</option><option value="x">X</option><option value="y">Y</option></select>
</div>
</div>
<div class="slice-field"><label>결과 파일명</label><input type="text" id="hole-output" placeholder="예: esp32_top_with_hole.stl"></div>
<button class="slice-btn" onclick="runAddHole()">구멍 뚫어서 새 파일로 저장</button>
</div>
<div class="slice-err" id="cad-err"></div>
<div class="slice-result" id="cad-result"></div>
</div>
</div>
<script>
function toggleTheme(){const d=document.documentElement;const n=d.getAttribute('data-theme')==='dark'?'light':'dark';d.setAttribute('data-theme',n);try{localStorage.setItem('homeclaw_theme',n);}catch{}}
function reloadFrame(){const f=document.getElementById('k2-frame');f.src=f.src;}
let loaded=false;
document.getElementById('k2-frame').addEventListener('load',()=>{loaded=true;});
setTimeout(()=>{ if(!loaded) document.getElementById('k2-err').classList.add('show'); },8000);
// ── K2 콤보 내장 카메라(자체 WebRTC 시그널링, 프린터 펌웨어가 직접 서빙) ──
// 프린터 자체는 :8000/call/webrtc_local 로 SDP offer를 POST하면 answer를 돌려주는
// 평문 HTTP 시그널링(Moonraker webcam 목록엔 안 잡힘 — 크리얼리티 자체 프로토콜).
// 홈클로는 https://ai.applecherry.net 로 서빙되므로 브라우저에서 직접 http://로
// fetch(POST)하면 mixed-content로 막힘("주의 요함" + 카메라 검은 화면, 2026-09-18
// 발견) — 그래서 게이트웨이의 /api/k2/webrtc-signal(같은 오리진, HTTPS)을 거쳐
// 서버가 대신 그 요청을 해준다.
function authH(){const t=(function(){try{return sessionStorage.getItem('smallclaw_token')||localStorage.getItem('smallclaw_token')||'';}catch{return '';}})();return t?{'Authorization':'Bearer '+t}:{};}
let camPC=null;
function setStatus(t){const s=document.getElementById('cam-status'); if(s) s.textContent=t;}
function connectCam(){
if(camPC){ try{camPC.close();}catch(e){} }
setStatus('연결 중...');
// STUN을 빼면(host candidate만) 이 프린터의 ICE 응답이 실제로는 안 옴(DTLS
// failed, bytesReceived 0) — 크리얼리티 데모 코드 그대로 STUN 유지해야 정상
// 동작함(2026-09-18 확인, 원인 불명이나 재현됨).
const pc=new RTCPeerConnection({iceServers:[{urls:'stun:stun.l.google.com:19302'}]});
camPC=pc;
pc.ontrack=(ev)=>{
const v=document.getElementById('k2-cam');
v.srcObject=ev.streams[0];
setStatus('실시간');
};
pc.oniceconnectionstatechange=()=>{
if(pc===camPC && (pc.iceConnectionState==='failed'||pc.iceConnectionState==='disconnected')){
setStatus('끊김');
}
};
// 원래는 ev.candidate===null(ICE gathering 완전 종료)까지 기다린 뒤에만 오퍼를
// 보냈는데, 이 네트워크에서 그 완전종료 신호가 20~30초씩 걸림(가상/VPN 인터페이스들을
// 하나씩 훑고 타임아웃되는 걸로 보임) — 정작 이 프린터가 필요로 하는 STUN srflx
// 후보 자체는 보통 1~2초 안에 잡힘. 그래서 완전종료를 기다리지 않고 짧은 타임아웃
// 뒤에 그때까지 모인 후보로 바로 보낸다(2026-09-19, 20초+ 연결지연 확인 후 수정).
let offerSent=false;
function sendOfferOnce(){
if(offerSent || pc!==camPC) return;
offerSent=true;
fetch('/api/k2/webrtc-signal',{
method:'POST',
headers:{'Content-Type':'text/plain', ...authH()},
body:btoa(JSON.stringify({type:'offer',sdp:pc.localDescription.sdp})),
}).then(r=>r.text()).then(txt=>{
const res=JSON.parse(atob(txt));
if(res.type==='answer' && pc===camPC){
pc.setRemoteDescription(new RTCSessionDescription(res));
}
}).catch(()=>{ if(pc===camPC) setStatus('연결 실패'); });
}
pc.onicecandidate=(ev)=>{
if(ev.candidate===null) sendOfferOnce(); // 빨리 끝나면 그대로 씀
};
pc.addTransceiver('video',{direction:'sendrecv'});
pc.createOffer().then(d=>pc.setLocalDescription(d)).then(()=>{
setTimeout(sendOfferOnce, 1500); // 안 끝나면 1.5초 뒤 그때까지 모인 후보로 진행
}).catch(()=>{ if(pc===camPC) setStatus('연결 실패'); });
}
function reconnectCam(){ connectCam(); }
connectCam();
// ── CAD(STL 확인) 모달 ──────────────────────────────────────────────────────
let cadCurrentFile=null;
let cadCurrentView='iso';
async function openCadModal(){
document.getElementById('cad-overlay').classList.add('show');
document.getElementById('cad-err').classList.remove('show');
document.getElementById('cad-result').classList.remove('show');
await cadLoadFileList();
}
function closeCadModal(){ document.getElementById('cad-overlay').classList.remove('show'); }
async function cadLoadFileList(){
const sel=document.getElementById('cad-file-select');
sel.innerHTML='<option value="">불러오는 중...</option>';
try{
const r=await fetch('/api/cad/list',{headers:authH()});
const d=await r.json();
const files=d.files||[];
if(!files.length){ sel.innerHTML='<option value="">워크스페이스에 STL 파일이 없습니다</option>'; return; }
sel.innerHTML=files.map(f=>`<option value="${f.replace(/"/g,'&quot;')}">${f}</option>`).join('');
if(cadCurrentFile && files.includes(cadCurrentFile)) sel.value=cadCurrentFile;
onCadFileChange();
}catch(e){
sel.innerHTML='<option value="">목록을 불러오지 못했습니다</option>';
}
}
function onCadFileChange(){
cadCurrentFile=document.getElementById('cad-file-select').value;
document.getElementById('cad-err').classList.remove('show');
document.getElementById('cad-result').classList.remove('show');
if(!cadCurrentFile){
document.getElementById('cad-info').textContent='';
document.getElementById('cad-preview-img').style.display='none';
document.getElementById('cad-placeholder').style.display='flex';
document.getElementById('cad-placeholder').textContent='파일을 선택하세요';
return;
}
cadLoadInfo();
cadRenderPreview();
}
async function cadLoadInfo(){
const infoEl=document.getElementById('cad-info');
infoEl.textContent='치수 확인 중...';
try{
const r=await fetch('/api/cad/info?path='+encodeURIComponent(cadCurrentFile),{headers:authH()});
const d=await r.json();
if(!r.ok) throw new Error(d.error||('HTTP '+r.status));
const b=d.bbox;
const size=[b.max[0]-b.min[0], b.max[1]-b.min[1], b.max[2]-b.min[2]].map(n=>n.toFixed(1));
infoEl.innerHTML='크기: <b>'+size.join(' × ')+' mm</b> · 삼각형 '+b.triangleCount+'개<br>'+
'X['+b.min[0].toFixed(1)+', '+b.max[0].toFixed(1)+'] Y['+b.min[1].toFixed(1)+', '+b.max[1].toFixed(1)+'] Z['+b.min[2].toFixed(1)+', '+b.max[2].toFixed(1)+']';
}catch(e){
infoEl.textContent='치수 조회 실패: '+e.message;
}
}
function cadSetView(view){
cadCurrentView=view;
document.querySelectorAll('.cad-view-btn').forEach(b=>b.classList.toggle('active', b.dataset.view===view));
cadRenderPreview();
}
async function cadRenderPreview(){
if(!cadCurrentFile)return;
const img=document.getElementById('cad-preview-img');
const placeholder=document.getElementById('cad-placeholder');
placeholder.style.display='flex'; placeholder.textContent='렌더링 중...';
img.style.display='none';
try{
const url='/api/cad/render?path='+encodeURIComponent(cadCurrentFile)+'&view='+cadCurrentView;
const r=await fetch(url,{headers:authH()});
if(!r.ok){ const d=await r.json().catch(()=>({})); throw new Error(d.error||('HTTP '+r.status)); }
const blob=await r.blob();
img.src=URL.createObjectURL(blob);
img.style.display='block';
placeholder.style.display='none';
}catch(e){
placeholder.textContent='렌더링 실패: '+e.message;
}
}
function toggleHoleForm(){
document.getElementById('cad-hole-form').classList.toggle('show');
}
async function runAddHole(){
const errEl=document.getElementById('cad-err');
const resultEl=document.getElementById('cad-result');
errEl.classList.remove('show'); resultEl.classList.remove('show');
if(!cadCurrentFile){ errEl.textContent='STL 파일을 먼저 선택하세요.'; errEl.classList.add('show'); return; }
const outputName=document.getElementById('hole-output').value.trim();
if(!outputName){ errEl.textContent='결과 파일명을 입력하세요.'; errEl.classList.add('show'); return; }
const dir=cadCurrentFile.includes('/')?cadCurrentFile.slice(0,cadCurrentFile.lastIndexOf('/')+1):'';
const body={
path:cadCurrentFile,
output_path:dir+outputName,
x:Number(document.getElementById('hole-x').value),
y:Number(document.getElementById('hole-y').value),
z:Number(document.getElementById('hole-z').value),
diameter:Number(document.getElementById('hole-diameter').value),
depth:Number(document.getElementById('hole-depth').value),
axis:document.getElementById('hole-axis').value,
};
try{
const r=await fetch('/api/cad/add-hole',{method:'POST',headers:{'Content-Type':'application/json',...authH()},body:JSON.stringify(body)});
const d=await r.json();
if(!r.ok||!d.success) throw new Error(d.error||('HTTP '+r.status));
resultEl.innerHTML='✅ 저장됨: <b>'+d.output_path+'</b>';
resultEl.classList.add('show');
await cadLoadFileList();
}catch(e){
errEl.textContent='구멍 뚫기 실패: '+e.message;
errEl.classList.add('show');
}
}
</script>
<!-- Three.js r128 UMD + 로더(Cura 스타일 3D 슬라이서 GUI용) — /vendor/three/ 정적 서빙 -->
<script src="/vendor/three/three.min.js"></script>
<script src="/vendor/three/STLLoader.js"></script>
<script src="/vendor/three/OrbitControls.js"></script>
<script type="module" src="/js/k2/slicer-view.js"></script>
</body>
</html>